你好metatable .__ len世界
关于Lua和 metatables 的初学者问题,举一个像Hello-World这样简单的示例,涉及到len
事件,不幸的是,该事件没有返回预期的结果(我正在使用Lua 5.1(从Ubuntu的官方存储库安装).
A beginner's question about Lua and metatables, with a example as simple as an Hello‑World, involving the len
event, which unfortunately does not returns the expected result (I'm using Lua 5.1 installed from Ubuntu's official repository).
这里是示例:
Test_Type = {};
function Test_Type.__len (o)
return 1;
end;
function new_test ()
local result = {};
setmetatable(result, Test_Type);
return result;
end;
do
local a_test = new_test();
print (#a_test);
print(getmetatable(a_test).__len(a_test));
end;
结果我得到:
0
1
我期望第一个打印语句显示1
,但是它显示0
,这让我大吃一惊.
I was expecting the first print statement to display 1
, but it displays 0
, to my big surprise.
我错过了什么?
根据 Lua参考手册—《元数据和元方法》 ,#
等效于此:
function len_event (op)
if type(op) == "string" then
return strlen(op) -- primitive string length
else
local h = metatable(op).__len
if h then
return (h(op)) -- call handler with the operand
elseif type(op) == "table" then
return #op -- primitive table length
else -- no handler available: error
error(···)
end
end
end
所以print (#a_test);
和print(getmetatable(a_test).__len(a_test));
应该得出相同的结果,对吗?
So print (#a_test);
and print(getmetatable(a_test).__len(a_test));
should result into the same, isn't it?
顺便说一句,为什么上面的《参考手册》摘录引用了metatable(op)
而应该是getmetatable(op)
?至少我已经尝试过print(metatable(a_test).__len(a_test));
,但最终会出错.
By the way, why is the above excerpt from the Reference Manual refers to metatable(op)
while it should be getmetatable(op)
? At least I've tried print(metatable(a_test).__len(a_test));
, and it ends into an error.
正如 Nneonneo 所注意到的,这是所使用的Lua版本的问题.似乎需要Lua 5.2才能起作用.
As Nneonneo noticed, this is an issue with the Lua version in use. Lua 5.2 seems to be required for the above to work.
来自 http://lua-users.org/wiki/LuaFaq :
为什么__gc和__len元方法不能在表上使用?
计划在5.2中支持表上的
__len
.参见LuaFiveTwo.
Why doesn't the __gc and __len metamethods work on tables?
__len
on tables is scheduled to be supported in 5.2. See LuaFiveTwo.
由于您使用的是5.1,因此表上的__len
不起作用.实际上,在Lua 5.2上运行代码会产生
Since you're using 5.1, __len
on tables does not work. Indeed, running your code on Lua 5.2 produces
1
1
符合预期.