简体   繁体   English

Lua通过C API使用可选的表值

[英]Lua using optional table values with the C API

I am passing a table { Value1=100, Value2=200, Value3=300, ...} from Lua to C. The following works great for my required values: 我正在将表{Value1 = 100,Value2 = 200,Value3 = 300,...}从Lua传递给C。以下代码非常适合我所需的值:

// Get the values from the table
lua_getfield(L, 2, "Value1");
lua_getfield(L, 2, "Value2");
lua_getfield(L, 2, "Value3");

const char *value_3 = luaL_checkstring(L, -1);
const char *value_2 = luaL_checkstring(L, -2);
const char *value_1 = luaL_checkstring(L, -3);

But I need to handle optional fields in the table, some of which may not be known at compile time - but will be known at run-time. 但是我需要处理表中的可选字段,其中某些字段可能在编译时未知,但在运行时会知道。 Based on all my searches, I think I need to use a metatable to replace the __index method on the table operated on by lua_getfield() to return NIL rather than throwing an error if a particular key is not found. 根据我的所有搜索,我认为我需要使用一个元表来替换lua_getfield()操作的表上的__index方法以返回NIL,而不是在未找到特定键的情况下抛出错误。 Then I could use luaL_checktype() to test for that. 然后,我可以使用luaL_checktype()进行测试。

I have used metatables with userdata with good success. 我已经将metatable与userdata一起使用,取得了很好的成功。 But despite that, I really have no idea how to go about this. 但是尽管如此,我真的不知道该怎么做。

No need to overcomplicate things. 无需过于复杂。 If you want to produce the default value in Lua, go for the metatable, but if you can get it in C, it is very easy. 如果要在Lua中生成默认值,请使用元表,但是如果可以在C中获取它,则非常简单。 lua_getfield produces nil if the key cannot be found in the table, so you can compare its return value with LUA_TNIL to check if it returned nil (or lua_isnil if you use an older API). 如果在表中找不到该密钥,则lua_getfield会产生nil ,因此您可以将其返回值与LUA_TNIL进行比较,以检查它的返回值是否为nil(如果使用较旧的API, lua_isnil )。 In that case, use your default value, or proceed with luaL_checkstring as usual. 在这种情况下,请使用默认值,或照常使用luaL_checkstring

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM