使用meta-tabl模拟对象:table.insert返回"表格预期,得到nil"

时间:2017-10-18 01:06:22

标签: object lua blackjack

所以,这就是情况。

我在命令行中制作二十一点游戏,所以我构建了一个玩家"对象"能够为用户和经销商(CPU)重复使用功能。整个游戏机制都在工作,除了分手的能力。所以,现在我正在通过我的整个游戏来增加玩家拥有多手牌的能力。

元表的构造如下:

function Player:new (o)
    o = o or {}   -- create object if user does not provide one
    setmetatable(o, self)
    self.__index = self
    self.total = 0 -- total of the hand (adding card values)
    self.money = 0 -- Remaining credits
    self.curHand = 1 -- Keeps track of the current hand being played and which bet to use
    self.split = 0 -- Keeps track of the total amount of times the hand was split (total number of hands)
    self.bet = {0, 0, 0, 0} -- 4 bets for the 4 possible hands after a Split
    self.insurance = 0 -- Amount being payed for insurance when dealer shows an Ace
    self.blackjack = false
    return o
end
然后,用户和经销商将被实例化:

user = Player:new({hand = {{}, {}, {}, {}}}) -- Instantiates the user and dealer objects
dealer = Player:new({hand = {}})

我的"击中"功能是我的问题开始的地方。

function Player:hit(deck)
    table.insert(self.hand[self.curHand], draw(deck))
end

如果我"橡皮鸭"问题,我的代码应该执行以下操作:

1. user.hand starts as a table containing user.hand[1] through [4]
2. user.curHand == 1
3. So, user.hand[user.curHand] == user.hand[1] (for now at least)
4. table.insert will then add the first card (returned from the function "draw") to user.hand[user.curHand] ... in other words the first table of the four.

在崩溃文本中,它告诉table.insert需要一个表,但是得到了nil,这意味着user.hand [1]上没有表...请记住在开始添加多个指针之前一切正常

我确信解决方案简单明了,但我不能因为我的爱而弄明白。从我的角度来看,一切都有意义才能发挥作用! (但是,计算机完全我们告诉他们做的事情......所以我知道我是这个问题)

感谢您的帮助!

0 个答案:

没有答案