通过用户输入将变量值保存到文件中
2014-4-15 14:51:41
收藏:0
阅读:126
评论:1
基本上,我有这段代码,当第一次运行时,它会打开一个渠道让用户输入配置文件中变量的值。
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"文件中,我不知道怎么做。
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
基本上,使用纯 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。