基本上我有这个代码,当第一次运行时,它会打开一个通道供用户在配置文件中输入变量的值
if (firstRun) then
Channel.New("First Configurations")
Channel:SendYellowMessage("Console","Running configuration sequence...\n How many potions would you like to buy?")
maxMP = io.read()
-- some more variables later
firstRun = false
end
上面的代码在我的主文件(“main.lua”)中,下面是我的配置文件(“config.lua”):
firstRun = true -- Change it to false if you want to manually configure
maxMP = nil -- How many MP potions would you like to buy?
maxHP = nil -- How many HP potions would you like to buy?
-- couple more variables
我需要它做的是,在运行firstRun Channel函数后,它会在“config.lua”文件中保存“maxMP”,“maxHP”等的值,同时保存firstRun = false。
我无法将其保存在.txt文件中,它必须位于“config.lua”中我只是不知道如何
答案 0 :(得分:1)
基本上,手动覆盖配置文件听起来像使用纯Lua的简单任务。
像这样(初始写入,对默认或当前配置做任何更改):
local function flush_config_to_file(configTable, configFile)
local tmpFileHandle
local configFileLines = {}
--start file with array declaration
table.insert(configFileLines, "local config = {")
--iterate default configs and put string analogical lines into table:
for key, value in pairs(defaultConfig) do
table.insert(configFileLines, "\t[\"key\"] = " .. tostring(value) .. ",")
end
--closing array:
table.insert(configFileLines, "}")
--returning table of config values:
table.insert("return config")
tmpFileHandle = io.open(configFile, "w")
--concat lines with \n separator and write those to file:
tmpFileHandle:write(table.concat(configFileLines, "\n"))
tmpFileHandle:close()
end
local function create_initial_config_file(configFile)
local defaultConfig =
{
"first_run" = true,
"maxMP" = nil,
"maxHP" = nil
-- etc etc etc
}
flush_config_to_file(defaultConfig, configFile)
end
local function get_config_from_module(configModule)
local tmpConfigTable
package.loaded[configModule] = nil
tmpConfigTable = require(configModule)
return tmpConfigTable
end
使用此代码段和config_file.lua:
local configModule = "config_file"
local configFile = configModule .. ".lua"
local tmpConfig = nil
create_initial_config_file(configFile)
-- Wall of text and logics I do not care about
-- Then user requires some configuration from file (module):
tmpConfig = getConfigFromModule(configModule)
-- User interaction or whatever which updates config:
tmpConfig.maxHP = io.read()
tmpConfig.first_run = false
-- etc etc
-- Rewrite config file with updated values:
flush_config_to_file(tmpConfig, configFile)
生成的初始config_file.lua文件内容应该是这样的:
local config = {
["first_run"] = true,
["maxMP"] = nil,
["maxHP"] = nil,
}
return config
注意:代码未经测试,仅显示Lua在某种配置下的易用性。
注2:了解Lua模块缓存' ref Seth Carnegie