通过用户输入将变量值保存到文件中

基本上,我有这段代码,当第一次运行时,它会打开一个渠道让用户输入配置文件中变量的值。

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函数后,将"maxMP"、"maxHP"等的值保存在"config.lua"文件中,并将firstRun = false保存。我不能保存在一个.txt文件中,它必须保存在"config.lua"文件中,我不知道怎么做。

点赞
用户1150918
用户1150918

基本上,使用纯 Lua 手动覆盖配置文件似乎是一个微不足道的任务。

类似这样(初始写入,对默认或当前配置进行任何更改):

local function flush_config_to_file(configTable, configFile)
    local tmpFileHandle
    local configFileLines = {}

    --以数组声明开始文件
    table.insert(configFileLines, "local config = {")

    --遍历默认配置,并将字符串类似行插入表中:
    for key, value in pairs(defaultConfig) do
        table.insert(configFileLines, "\t[\"key\"] = " .. tostring(value) .. ",")
    end

    --关闭数组:
    table.insert(configFileLines, "}")

    --返回配置值的表:
    table.insert("return config")

    tmpFileHandle = io.open(configFile, "w")

    --使用 \n 分隔符连接行并将其写入文件:
    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

        --等等等等
    }

    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)

--一堆文本和逻辑我不在意

--然后用户从文件(模块)中获取一些配置:
tmpConfig = getConfigFromModule(configModule)

--更新配置的用户交互或其他内容:
tmpConfig.maxHP = io.read()
tmpConfig.first_run = false
--等等

--使用更新的值重新写入配置文件:
flush_config_to_file(tmpConfig, configFile)

生成的初始 config_file.lua 文件内容应该类似于:

local config = {
    ["first_run"] = true,
    ["maxMP"] = nil,
    ["maxHP"] = nil,
}

return config

注意:代码未经测试,仅展示使用 Lua 进行某种配置的简单用法。

注意 2:请注意 Lua 模块缓存:参考资料Seth Carnegie

2014-04-15 16:16:08