Emperor Ansem
Emperor Ansem

Reputation: 3

Can i make a function to create table and name it with a parameter used when called?

I'm trying to make a function that, when I call it, I can pass it a name and it will make a table for me. I then want it to return the table so I can use it. My code does make a table but I can't seem to access it. I'm thinking Lua is having trouble naming after an argument, but I'm not sure how to fix it. Here is a sample code of what I am trying to accomplish:

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)

And thats about it. I'm trying to make a vector class (not sure why one isn't in Lua), but even without vectors I want to be able to pass names into functions. What should i do?

Upvotes: 0

Views: 677

Answers (1)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

You can make function create named table in global, but why would you ever need that? Just return it and assign it to whatever you like be it global or local or whatever. Globals are bad anyway.

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)

Upvotes: 1

Related Questions