Lua 使用带有 C API 的可选表值 | 珊瑚贝

Lua using optional table values with the C API


我正在将一个表 { Value1=100, Value2=200, Value3=300, …} 从 Lua 传递到 C。以下内容非常适合我所需的值:

1
2
3
4
5
6
7
8
// 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);

但我需要处理表中的可选字段,其中一些在编译时可能不知道 – 但会在运行时知道。根据我所有的搜索,我认为我需要使用元表来替换 lua_getfield() 操作的表上的 __index 方法以返回 NIL,而不是在找不到特定键时抛出错误。然后我可以使用 luaL_checktype() 来测试。

我已经成功地使用了带有 userdata 的元表。但尽管如此,我真的不知道该怎么做。

  • lua_getfield 会抛出错误吗?
  • 参观,阅读如何提问,以及最小的可重复示例。几乎完美的问题陈述,除了你需要实际提出问题。
  • 不,但是 luaL_checkstring() 会抛出一个错误。 5.2 版 lua_getfield() 是一个 void 函数。这在 5.3 中发生了变化,它现在返回类型,包括 nil/0 如果在表中找不到键。我正在使用 5.3 库,但指的是 5.2 参考手册。


没有必要把事情复杂化。如果您想在 Lua 中生成默认值,请使用元表,但如果您可以在 C 中获取它,则非常容易。如果在表中找不到键,则 lua_getfield 会生成 nil,因此您可以将其返回值与 LUA_TNIL 进行比较,以检查它是否返回 nil(如果使用较旧的 API,则返回 lua_isnil)。在这种情况下,请使用您的默认值,或像往常一样继续使用 luaL_checkstring。

  • 感谢您的答复。我的问题是我指的是我购买了印刷版的 5.2 参考手册。在 5.2 版中,lua_getfield() 是一个 void 函数。我似乎在 5.3 中发生了变化——这是我实际使用的。是的,只需检查返回值就可以解决我的问题。谢谢!
  • 为了完整起见,在 Lua 5.2 和更早版本中,您可以在值上使用 lua_type ,这会给您相同的结果。


来源:https://www.codenong.com/52347182/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9236.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?