如何在Lua中的函数内添加表

时间:2015-07-25 05:00:12

标签: lua

我想做: function objects:add(namespace, x, y, w, h, mode, density, r) 然后制作一张新桌子。 objects.namespace = {} 然后返回表格: return objects.namespace 但我想要'命名空间'在功能中定义实际 ...我将如何做到这一点? 当我试着在桌子里面打电话的时候.E:print(objects.newBox.x) 它给了我' NIL'

即使我尝试:

function test(name)
  print(name)
  [name] = {"yo"}
end
test(doit)

它给了我一个错误:'尝试索引零值' 我一定做错了......

table = {}
function table:add(name, x, y)
  table.[name] = {}
  table.[name].x = x
  table.[name].y = y

  return table.[name]
end
table:add(box1, 300, 100)
print("table.box1.x: " ..table.box1.x)
print("table.box1.y: " ..table.box1.y)

-- [name] is to be defined in the function arg.
-- then i want to return the table and use it's contents for other uses I.E line 10 and 11
-- gets the following error: '<name>' expected near '['

1 个答案:

答案 0 :(得分:1)

这是一个工作版本:

t = {}
function t:add(name, x, y)
  t[name] = {} -- or use  t[name] = {x=x, y=y} and remove the  next 2 lines
  t[name].x = x
  t[name].y = y
  return t[name] -- necessary?
end

t:add('box1', 300, 100)

print("t.box1.x: " ..t.box1.x)
print("t.box1.y: " ..t.box1.y)
  • 命名变量table会隐藏表库,因此我将其更改为t
  • 当您致电t:add(box1, 300, 100)时,未定义box1,因此其值为nil,这不是表格的有效密钥
  • 您希望使用"box1"作为密钥,因为t.box1只是t["box1"]
  • 的糖
  • 在您的函数t:add中,您希望使用name的值对t编索索引,语法为t[name]
  • 您也没有使用返回值,您可以使用tt.box1转到该值。似乎没必要
  • 使用:建议你想要实现对象?如果是这种情况,请参阅PIL Object Oriented Programming以获取有关如何实施该
  • 的介绍
相关问题