在Lua中引用包含表的函数
2012-9-20 15:15:14
收藏:0
阅读:146
评论:2
我有一个辅助函数,返回以下表格:
function of_type(expected_type)
return {
expected = expected_type,
matches = function(value) return type(value) == expected_type end,
describe = "type " .. expected_type
}
end
现在,这对其他匹配器来说没问题,但在这里,当调用matches函数时,我想将type(value)存储到同一表格中的一个字段中。 像这样:
function of_type(expected_type)
return {
expected = expected_type,
mismatch = nil, --在初始化时将其设置为nil
matches = function(value)
mismatch = type(value) --如何实现呢?
return type(value) == expected_type
end,
describe = "type " .. expected_type
}
end
这可能吗?
点赞
用户734069
你不能。嗯,除非在函数中存储表的一份副本,或将表作为参数传递给函数。在表构造函数的所有语句被处理之前,表还不存在。而且由于你没有在任何地方存储它(在该函数中),你的函数无法命名它以便找到它。
因此,你应该给它一个名字,即使只是暂时的:
function of_type(expected_type)
local temp = nil
temp = {
expected = expected_type,
mismatch = nil, -- 在初始化时将其设置为nil
matches = function(value)
temp.mismatch = type(value) -- 就像这样
return type(value) == expected_type
end,
describe = "type " .. expected_type
}
return temp
end
这有效是因为 Lua 将 temp 存储为一个上值。因此,你创建的函数将看到 temp 的变化,例如当你将其设置为一个表值时。而且由于它是一个局部变量,它在该函数之外是不可见的。
2012-09-20 15:26:56
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的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中获取用户配置主目录的跨平台方法
是的,但你需要分为几个步骤:
function of_type(expected_type) local tbl = { expected = expected_type, mismatch = nil, -- 在初始化时将其设置为 nil describe = "type " .. expected_type } tbl.matches = function(value) tbl.mismatch = type(value) return type(value) == tbl.expected end return tbl end -- 测试输出 local foo = of_type("string") print(foo.matches(1), foo.matches("1"))这应该会像预期的那样输出
false true。实质上,
tbl.matches将存储对tbl的引用(它被称为“上值”),并且能够修改该表中的所有字段(包括它自己的引用)。另一种方法是以下方法(注意 tbl.matches 函数中的更改)。 您可不必将其捕获为上值,还可以使用
tbl:method语法并将tbl作为隐式self参数传递:function of_type(expected_type) local tbl = { expected = expected_type, mismatch = nil, -- 在初始化时将其设置为 nil describe = "type " .. expected_type } function tbl:matches(value) self.mismatch = type(value) -- 怎么做的? return type(value) == self.expected end return tbl end local foo = of_type("string") print(foo:matches(1), foo:matches("1"))这将输出相同的结果。请注意,您使用
foo:matches表示法使foo作为第一个参数(在该方法中作为self引用)进行传递。这与使用foo.matches(foo, 1)相同。