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

时间:2018-09-15 17:28:35

标签: c lua

我正在将表{Value1 = 100,Value2 = 200,Value3 = 300,...}从Lua传递给C。以下代码非常适合我所需的值:

private void Button_Click(object sender, RoutedEventArgs e)
{
 string textBoxValue = MessageTextBox.Text;

 if (string.IsNullOrWhiteSpace(textBoxValue))
 {
   // Display an error or warning message to ask user to enter some text.
    return;
 }
 else
 {
   foreach(char ch in textBoxValue)
   {
       // Now you have each character of the text entered in the textbox
       // You can write your logic now.
   }
 }
}

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

我已经成功地将metatables与userdata一起使用。但是尽管如此,我真的不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

无需太复杂。如果要在Lua中生成默认值,请使用元表,但是如果可以在C中获取它,则非常简单。如果无法在表中找到密钥,则lua_getfield会产生nil,因此您可以将其返回值与LUA_TNIL进行比较,以检查它是否返回nil(如果使用,则返回lua_isnil较旧的API)。在这种情况下,请使用默认值,或照常继续进行luaL_checkstring