如何使用动态变量名?

Bnh*_*bq7 2 lua coronasdk

我按以下方式设置本地动态变量名称 _local["cracks"..brick.index] = ...

我怎么能访问变量来做例如removeSelf?我试过的 _local["cracks"..brick.index]:removeSelf()

Tom*_*get 5

_local["cracks"..brick.index]:removeSelf()
Run Code Online (Sandbox Code Playgroud)
  1. 索引_local作为一个表"cracks"..brick.index来获取值,调用它t
  2. 索引t作为一个表"removeSelf"来获取另一个值,调用它m
  3. m作为一个方法调用t,就像调用一样m(t)

要做到这一点,你必须做这样的事情:

_local["cracks"..brick.index] = 
{ 
    removeSelf = function(self)
        --do something with self, 
        --which refers to the table that removeSelf is a member of (the {})
        return --something if wanted 
    end 
}
Run Code Online (Sandbox Code Playgroud)

通常,使用function t:m() end隐式声明self参数的语法定义方法.但是,如果没有实际的t变量,你就不能这样做,在这种情况下没有.

或者,明确地说

local tabl = {}
function tabl:removeSelf()
    --do something with self, 
    --which refers to the table that removeSelf is a member of (tabl)
    return --something if wanted 
end 

_local["cracks"..brick.index] = tabl
Run Code Online (Sandbox Code Playgroud)

如果这不能解释您的问题,请在问题中添加更多代码.