Lua用户数据:无法同时进行数组访问和方法 [英] Lua userdata: Unable to have simultaneous array access and methods
问题描述
我遇到了这个人的问题: Lua用户数据数组访问和方法
I had this guy's problem: Lua userdata array access and methods
其中,当我设置用户数据的元表的__index时,它始终称为getter,而不是未为元事件声明的其他方法.上面链接的解决方案是在Lua中进行的,我尝试了一个看起来不太优雅的C实现,但是无论如何,它产生了一个新问题,因为我的新方法不再可以接受参数,并且出现了以下错误:
wherein when I set the __index of my userdata's metatable, it always called the getter, instead of my other methods that weren't declared for meta-events. The solution to the above link is in Lua, and I attempted a C implementation which seems inelegant, but regardless, it creates a new problem in that my new methods can no longer take arguments, and I get this error:
attempt to call method 'asTable' (a table value)
关于此Lua声明:
print_r(c:asTable() )
这是我进行所有设置的方式:
This is how I set everything up:
//Methods, many of which are overridden Lua meta-events (with the underscores)
static const struct luaL_reg vallib_m [] = {
{"asTable", PushLuaTable}, //these functions are not called
{"asCopy", CopyLuaVal},
{"__newindex", SetLuaVal},
{"__index", GetLuaVal},
{"__tostring", ValToString},
{"__gc", GarbageCollectVal},
{"__metatable", HideMetaTable},
{NULL, NULL}
};
//Static library functions
static const struct luaL_reg vallib_f [] = {
{"specialprint", PrintVals},
{NULL, NULL}
};
int luaopen_custom(lua_State *L)
{
luaL_newmetatable(L, "custom.Value");
lua_pushstring(L, "__index");
lua_pushvalue(L, -2); /* pushes the metatable */
lua_settable(L, -3); /* metatable.__index = metatable */
luaL_register(L, NULL, vallib_m);
luaL_register(L, "special", vallib_f);
return 0;
}
然后在默认情况下(通过__index调用)的getter中,我首先检查要调用的其他事件,然后将控制权转移给它们.请注意,我从堆栈中删除了包含函数名称的参数.
Then in my getter, which is called by default (via __index), I first check for other events that I intended to be called and transfer control to them as follows. Note that I remove the argument containing the name of the function from the stack.
//TODO: this is a tentative fix, I would rather do this with metatables
//checking for methods
if (lua_isstring(L, 2))
{
field = luaL_checkstring(L, 2);
if (unlikely(!field))
{
reporter->Warning("Fail in getter -- bad string as method attempt");
return LUA_FAILURE;
}
if (strcmp(field, "asTable") == 0)
{
lua_remove(L, 2); //delete string "asTable"
return PushLuaTable(L);
}
else if (strcmp(field, "asCopy") == 0)
{
lua_remove(L, 2); //delete string "asCopy"
return CopyLuaVal(L);
}
//... other methods.
else
{
//Insert string back into stack??
}
}
无论传递多少参数,它都不会将我的方法视为函数,并且即使有任何括号或冒号也会引发错误. (可以通过c.asTable
进行访问,对于不带参数的方法,我很满意,但是我计划添加一些带参数的方法,而无论语法是否与方法不一致.
It doesn't treat my method as a function regardless of how many arguments are passed, and throws an error if there are even any parentheses or a colon. (It can be accessed by c.asTable
, which works fine for methods that takes no arguments but I plan to add some that do, and regardless, the syntax is inconsistent with methods.
无论如何,最好不要通过我的C getter调用这些函数,而应使用元表来解决.如果可能的话,请提供使用C API的示例-Lua中已经有StackOverflow解决方案,但是我无法将它们转换为C.
In any case, it would be preferable to NOT call these functions through my C getter, and instead solve this with metatables. If this is possible, please provide an example using the C API -- there are already StackOverflow solutions in Lua, but I haven't been able to translate them to C.
推荐答案
要从Lua访问C结构的字段,您需要一个函数作为__index
元方法,因为您需要访问userdata对象,并且如果__index
是表,则不会得到它:
For accessing fields of a C struct from Lua you'll need a function as the __index
metamethod, because you need access to the userdata object, and you won't get it if __index
is a table:
-- Lua example code; obj* should be userdatas ...
-- an example __index function
local function anIndex( o, k )
print( "accessing", k, "in", o )
return 1
end
local obj = {}
local meta = { __index = anIndex }
setmetatable( obj, meta )
print( obj )
--> table: 0xfcb060
print( obj.x )
--> accessing x in table: 0xfcb060
--> 1
这对于属性很好,但是对于访问由相同类型的所有用户数据共享的方法来说,这是不舒服的(效率低下). __index
表可能会更好:
This works fine for properties, but it's uncomfortable (and inefficient) for accessing methods shared by all userdatas of the same type. An __index
table would be better for that:
-- an example method
local function aMethod( o )
print( "calling aMethod on", o )
return 2
end
local obj2 = {}
local methods = { aMethod = aMethod }
local meta2 = { __index = methods }
setmetatable( obj2, meta2 )
print( obj2 )
--> table: 0xfcada0
print( obj2:aMethod() )
--> calling aMethod on table: 0xfcada0
--> 2
但是现在我们两个都想要!
But now we want both!
元方法可以在Lua中链接,因此我们可以尝试将__index
函数设置为__index
表(在本例中为methods
)的备用:
Metamethods can be chained in Lua, so we could try to set an __index
function as fallback for the __index
table (methods
in this case):
setmetatable( methods, meta )
print( obj2 )
--> table: 0xfcada0
print( obj2.x )
--> accessing x in table: 0xfcade0
--> 1
print( obj2:aMethod() )
--> calling aMethod on table: 0xfcada0
--> 2
但是,如果您仔细观察,您会发现__index
函数获得的对象与obj2
...不同.
But if you look closer, you'll see that the __index
function gets a different object than obj2
...
print( methods )
--> table: 0xfcade0
它改为将methods
表作为第一个参数.因此,我们无法访问原始用户数据(在此示例中为表),并且实际上无法查找任何字段.这样就行不通了.
It gets the methods
table as the first argument instead. So we lose access to the original userdata (table in this example), and we can't actually look up any fields. So that won't work.
setmetatable( methods, nil ) -- let's undo this ...
幸运的是,__index
函数可以执行任意操作,包括访问另一个表(例如,存储在高值值中的表):
Fortunately, an __index
function can do arbitrary things, including accessing another table (e.g. one that's stored in an upvalue):
local obj3 = {}
local meta3 = {
__index = function( o, k )
local v = methods[ k ] -- methods is an upvalue here
if v == nil then
print( "accessing", k, "in", o )
v = 1
end
return v
end
}
setmetatable( obj3, meta3 )
print( obj3 )
--> table: 0xfc23a0
print( obj3.x )
--> accessing x in table: 0xfc23a0
--> 1
print( obj3:aMethod() )
--> calling aMethod on table: 0xfc23a0
--> 2
现在效果很好!
万一这种情况经常发生,我们可以编写一个辅助函数,为我们创建一个合适的__index
函数.作为参数传递的indexfunc
仅与字段查找有关,而根本不需要处理方法.生成的函数将执行以下操作:
Now this worked great!
In case this happens more often, we could write a helper function that creates an appropriate __index
function for us. The indexfunc
that's passed as argument is only concerned with field lookup, and doesn't have to handle methods at all. The generated function will do that:
local function makeindex( methodstable, indexfunc )
return function( o, k )
local v = methodstable[ k ]
if v == nil then
v = indexfunc( o, k )
end
return v
end
end
local obj4 = {}
local meta4 = { __index = makeindex( methods, anIndex ) }
setmetatable( obj4, meta4 )
print( obj4 )
--> table: 0xfc92b0
print( obj4.x )
--> accessing x in table: 0xfc92b0
--> 1
print( obj4:aMethod() )
--> calling aMethod on table: 0xfc92b0
--> 2
如果尝试将其转换为Lua C API,您会发现采用luaL_Reg
数组而不是方法表和使用lua_CFunction
指针而不是Lua的堆栈索引更为方便功能.这就是luaL_setfuncs()
之类的所有方法设置upvalue).
If you try to translate that to the Lua C API, you'll see that it's more convenient to take a luaL_Reg
array instead of a methods table, and a lua_CFunction
pointer instead of a stack index to a Lua function. And this is what the moon_propindex()
function linked in this answer does (additionally it let's you set upvalues for all methods like luaL_setfuncs()
).
这篇关于Lua用户数据:无法同时进行数组访问和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!