【问题标题】:How do i add tables inside of a function in Lua如何在 Lua 中的函数内添加表
【发布时间】:2015-07-26 01:15:53
【问题描述】:

我正在尝试做: function objects:add(namespace, x, y, w, h, mode, density, r) 然后做一个新表。 objects.namespace = {} 然后通过以下方式返回表格: return objects.namespace 但我希望在函数中实际上定义“命名空间”......我将如何去做呢? 当我尝试调用表格内的某些内容时:print(objects.newBox.x) 它给了我'NIL'

即使我尝试:

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

它给了我一个错误:'试图索引一个 nil 值' 我一定是做错了什么……

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 '['

【问题讨论】:

  • objects[namespace] = {}
  • 每当我尝试`objects[namespace] = {} objects[namespace].x = x` 我得到错误:'objects[namespace] = { 行上的'table index is nil' }'
  • 你怎么打电话给objects:add
  • 将此作为函数中的第一条语句插入,以便在更好的地方获得错误并提供更好的消息:assert(namespace and namespace == namespace,'namespace cannot be nil or NaN'),或者,如果你是这个意思,assert(string.find(namespace,'^[_%a][_%w]*$'),'namespace must be an identifier')
  • 请尝试创建一个MCVE。很难(至少对我来说)知道没有它你想做什么。

标签: lua


【解决方案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 中,您想用名称值索引t,语法为t[name]
  • 您也没有使用返回值,您可以从tt.box1 获取它。好像没必要
  • 使用: 建议您要实现对象?如果是这种情况,请参阅 PIL Object Oriented Programming 了解如何实现它

【讨论】:

  • 非常感谢您的回答以及有用的反馈和提示:D 太棒了!!
猜你喜欢
  • 2014-01-31
  • 2021-01-14
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 2022-01-23
  • 2012-05-03
  • 2019-11-22
相关资源
最近更新 更多