0

我对 lua 很陌生,我的计划是创建一个表。这个表(我称之为测试)有 200 个条目 - 每个条目都有相同的子条目(在这个例子中子条目金钱和年龄):

这是一种伪代码:

table test = {
    Entry 1: money=5 age=32
    Entry 2: money=-5 age=14
    ...
    Entry 200: money=999 age=72
}

我怎么能用 lua 写这个?有没有可能?另一种方法是,我将每个子条目写为一个表:

table money = { }
table age = { }

但对我来说,这不是一个好方法,所以也许你可以帮助我。

编辑:

这个问题Table inside a table是相关的,但我不能写这个 200x。

4

3 回答 3

4

试试这个语法:

test = {
  { money = 5, age = 32 },
  { money = -5, age = 14 },
  ...
  { money = 999, age = 72 }
}

使用示例:

-- money of the second entry:
print(test[2].money) -- prints "-5"

-- age of the last entry:
print(test[200].age) -- prints "72"
于 2012-10-02T11:39:19.123 回答
0

您也可以将问题放在一边,并在test:中有两个序列,money并且age每个条目在两个数组中都有相同的索引。

test = {
   money ={1000,100,0,50},
   age={40,30,20,25}
}

这将具有更好的性能,因为您只有3表而不是n+1表的开销,其中n是条目数。

无论如何,您必须以一种或另一种方式输入数据。您通常会使用一些易于解析的格式,如 CSV、XML 等,然后将其转换为表格。像这样:

s=[[
1000 40
 100 30
   0 20
  50 25]]
test ={ money={},age={}}
n=1
for balance,age in s:gmatch('([%d.]+)%s+([%d.]+)') do
   test.money[n],test.age[n]=balance,age
   n=n+1
end 
于 2012-10-02T12:43:10.157 回答
0

你的意思是你不想把“钱”和“年龄”写成200倍?

有几种解决方案,但您可以编写如下内容:

local test0 = {
  5, 32,
  -5, 14,
  ...
}

local test = {}

for i=1,#test0/2 do
  test[i] = {money = test0[2*i-1], age = test0[2*i]}
end

否则,您总是可以使用元表并创建一个行为与您想要的完全一样的类。

于 2012-10-02T15:42:45.887 回答