Lua表的备用值(整个表)
2018-7-27 20:23:0
收藏:0
阅读:117
评论:1
我相信答案是“不行”,但我还是需要问一下:
我有几个嵌套的值表,大多数都具有相同的“架构”(名称层次结构)。 例如,theme.person.child在这些嵌套表中的每个表中都有一个值,例如像“#ffcc33”这样的字符串。
有时,我想能够引用theme.person(通常是表格)并“获取”字符串值而不是名称。 我想要一个所有person的默认值,而不管子键如何。
是否有任何元方法/键可以让我在table.person.child和table.person上调用相同的函数并始终获取字符串? 在代码中:
local theme1 = { person = { child='#ffcc33', adult='#00ffff', _default='#ff0000' } }
local theme2 = { person = '#ff0000' }
for _,theme in ipairs{ theme1, theme2 } do
print(somefunction(theme))
end
是否有任何方法可以使两个打印语句输出#ff0000? 除了:
function somefunction(x) return type(x)=='table' and x._default or x end
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的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 代码?

这里用的方式有点奇怪,但是这是你想要的吗?
person必须是硬编码属性,或者如果它们是一个表格,你想要在所有属性中搜索_default吗?local theme1 = { person = { child='#ffcc33', adult='#00ffff', _default='#ff0000' } } local theme2 = { person = '#ff0000' } function somefunction(tbl, param) if type(tbl) == 'string' then return tbl end return tbl._default end for _,theme in ipairs{theme1, theme2} do print(somefunction(theme.person)) endcodepad
你可以使用 元表,如果有一个标准,你想要使用它,但然后必须在每个表上设置它们。
__tostring用于元表,它允许在将表转换为字符串时返回任何你想要的字符串。在下面的代码中,我在theme1的person上设置了元表,以便在对表执行tostring()时返回_default。__index让你可以在表被索引时返回任何值。在这里,它像一个color属性,如果person是一个表,则返回person._default,否则返回person。local personmt = { __tostring = function(t) if type(t) == 'table' and t._default ~= nil then return t._default end return tostring(t) end } local thememt = { __index = function(t, k) if k == 'color' then if type(t.person) == 'table' then return t.person._default end return t.person end end } local theme1 = { person = { child='#ffcc33', adult='#00ffff', _default='#ff0000' } } local theme2 = { person = '#ff0000' } setmetatable(theme1.person, personmt) for _,theme in ipairs{ theme1, theme2 } do setmetatable(theme, thememt) print('theme.person (__tostring):', theme.person) print('theme.color (__index) :', theme.color) endcodepad