如何使用元表将每个索引更改为表?
我正在尝试编写一个元表,以便表中的所有索引都上移一个位置(即 t[i]
应返回 t[i+1]
)。我需要这样做,因为该表是使用索引 1 作为第一个元素定义的,但我必须与使用索引 0 作为第一个元素的程序进行交互。自从阅读《Lua 编程》后,我认为我可以使用代理表完成我想要的事情,但我似乎无法让它工作。到目前为止,我有这个:
t = {"foo", "bar"}
local _t = t
t = {}
local mt = {
__index = function(t, i)
return _t[i+1]
end
}
setmetatable(t, mt)
但是,这并没有产生预期的结果。事实上,它根本不返回任何值(每次查找都是nil
)。有没有更好的方法来做到这一点,或者我只是错过了一些东西?
I'm trying to write a metatable so that all indexes into the table are shifted up one position (i.e. t[i]
should return t[i+1]
). I need to do this because the table is defined using index 1 as the first element, but I have to interface with a program that uses index 0 as the first element. Since reading Programming in Lua, I think that I can accomplish what I want with a proxy table, but I can't seem to get it working. So far, I have this:
t = {"foo", "bar"}
local _t = t
t = {}
local mt = {
__index = function(t, i)
return _t[i+1]
end
}
setmetatable(t, mt)
However, this does not create the expected result. In fact, it doesn't return any values at all (every lookup is nil
). Is there a better way to do this, or am I just missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里运行时为我输出“foo”: http://www.lua.org/cgi-bin /演示
outputs "foo" for me when run here: http://www.lua.org/cgi-bin/demo