出于语法原因,我想编写如下函数LUA:
on update()
--do something
end
而不是常规的:
function update()
--do something
end
是否可以(实际上(将"function"关键字键入定义或别名为"on"?
不,这是不可能的,除非您在加载程序之前处理 Lua 输入以将on
替换为function
。
我建议考虑替代方案,例如
on.update = function ()
-- do something
end
-- on can simply be an alternative name
-- for the global environment
on = _G
或将程序定义为字符串
-- Update functions is defined as a string, loaded later.
on.update = [[
-- do something
]]
要使后者起作用,您必须设置__newindex
元方法,通过load
字符串并将生成的函数设置为字段值,从字符串创建新函数。
在 llex.c 中luaX_init末尾添加这些行并重建 Lua:
{
TString *ts = luaS_new(L, "on");
luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */
ts->extra = cast_byte(TK_FUNCTION+1-FIRST_RESERVED); /* reserved word */
}