简体   繁体   English

尝试在Lua中调用函数时出现Nil错误

[英]Nil error when trying to call a function in Lua

I'm getting a strange error that I can't for the life of me crack. 我遇到了一个奇怪的错误,我无法终生破解。

I'm coding a card game and I have two tables of different lengths. 我正在编写纸牌游戏,并且有两个长度不同的桌子。 One links entries to functions, and the other holds the played cards. 一个将条目链接到功能,另一个则保存已玩的卡。 The first table is for attributes that certain cards in the deck have. 第一个表用于卡组中某些卡牌具有的属性。

ATTRIBUTES = {  
        Reset   = RuleBook.Do_Reset,
        Go_Lower= RuleBook.Do_Go_Lower,
        Mirror  = RuleBook.Do_Mirror}

The way these functions are called is as follows: 这些函数的调用方式如下:

ATTRIBUTES[cardPile[#cardPile].Attribute]()

I've printed out of contents of both the card object and the ATTRIBUTES table and both are completely in tact. 我已经打印出卡片对象和ATTRIBUTES表的内容,并且两者都完好无损。 Cards that have an attribute have a table entry under Attribute for a function, and those link up to the Do_... functions. 具有属性的卡在功能的“属性”下具有一个表条目,这些卡链接到Do _...函数。 Yet the above line of code doesn't appear to work. 但是上面的代码行似乎不起作用。 If anyone has ideas or suggestions they'd be appreciated. 如果有人有想法或建议,将不胜感激。

Lua lets you basically use any kind of lua value as a key in a table. 通过Lua,您基本上可以将任何类型的lua值用作表中的键。 The problem with your code above is that your ATTRIBUTE table uses strings as the key but cardPile[#cardPile].Attribute is a function NOT a string. 上面代码的问题是,您的ATTRIBUTE表使用字符串作为键,但是cardPile[#cardPile].Attribute是一个函数,而不是字符串。

When you perform the lookup here: 当您在此处执行查找时:

ATTRIBUTES[cardPile[#cardPile].Attribute]()

You're saying lookup the corresponding value in ATTRIBUTES having the key cardPile[#cardPile].Attribute which is a function. 您说的是在具有键cardPile[#cardPile].Attribute它是一个函数)的ATTRIBUTES中查找相应的值。 Your ATTRIBUTES table as you have it defined only contain strings as keys -- it has no functions as keys so nil is returned. 定义的ATTRIBUTES表仅包含字符串作为键-它不具有任何键功能,因此返回nil。

Two possible fixes for this: 对此的两个可能的修复:

Assuming cardPile 's Attribute field already refers to the function you want, you can just call it like this: 假设cardPileAttribute字段已经引用了您想要的功能,则可以像这样调用它:

cardPile[#cardPile].Attribute()

The alternative is to change how you setup card_obj 's Attribute field -- make it refer to a string instead of the the function: 另一种方法是更改​​设置card_objAttribute字段的方式-使它引用字符串而不是函数:

function Card.Create(Suit, Number, Name)
  local card_obj = {}
  -- ...
  if( card_obj.number == 1 ) then
    card_obj.Attribute = "Reset"
  elseif( card_obj.number == 6 ) then
    card_obj.Attribute = "Go_Lower"
  -- ... etc.
  else
    card_obj.Attribute = nil;
  end
end

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

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