我正在尝试创建一个函数,当我调用它时,我可以传递一个名称,它将为我创建一个表。然后我希望它返回表格,以便我可以使用它。我的代码确实创建了一个表,但我似乎无法访问它。我认为Lua在争论后命名有困难,但我不确定如何修复它。以下是我要完成的示例代码:
Tablemaker.lua:
Tabler = {}
Tabler.init = function (n,x,y,z)
--This is where i think it is messing up
N = {}
N.a = x
N.b = y
N.c = z
--had a print function here so i know the table is made.
I am leaving it out for you guys.
--not sure if i need it but i put return here.
Return n
End
Main.lua:
Require ("Tablemaker.lua")
Tabler.init (meow,15,32,45)
--a sepaeate print function here to verify i can access my
table. When the console tries to print, it gives meow = nil.
Which i am assuming the table is not properly named meow and
is instead named n. However using print(n.a) for example gives
n = nil also.
Print(meow.a .. " " .. meow.b .. " " .. meow.c)
就是这样。我正在尝试创建一个矢量类(不确定为什么一个不在Lua中),但即使没有矢量我也希望能够将名称传递给函数。我该怎么办?
答案 0 :(得分:1)
你可以让函数在全局创建命名表,但为什么你需要呢?只需将其归还并将其分配给您喜欢的全球或本地或其他任何内容。无论如何,全局都很糟糕。
Tabler = {}
Tabler.init = function (x,y,z)
N = {}
N.a = x
N.b = y
N.c = z
Return N
End
Require ("Tablemaker.lua")
local meow = Tabler.init(15,32,45)
Print(meow.a .. " " .. meow.b .. " " .. meow.c)