RoyStanford
RoyStanford

Reputation: 43

Getting a table from a class in Lua

Quick question, how would I get the table called props from the SimpleClass variable?

local SimpleClass = {}
local SimpleClass_mt = {__index = SimpleClass}

function SimpleClass:new()
    local props = {name = " yolo"}
    setmetatable(props, SimpleClass_mt)
    return props
end

--get props from SimpleClass here

--my attempt here
local propsFromSimpleClass = getmetatable(SimpleClass)--clearly won't work

Upvotes: 2

Views: 81

Answers (2)

Oliver
Oliver

Reputation: 29591

A "props" table is returned by SimpleClass:new(): this function mimics creating a new "instance" of "class" SimpleClass. Hence if you do

p = SimpleClass:new()

then p is the props table instance created by the new(self) function of SimpleClass table:

print(p.name) 

will print "yolo".

It is important to understand that you get a new table, which inside SimpleClass:new() is bound to a local var called "props", every time you call SimpleClass:new(). But you can't get "the props table from SimpleClass": the table that was referenced by props in SimpleClass.new(self) represents an instance of SimpleClass class. The SimpleClass table does not have a table called props.

Upvotes: 1

maček
maček

Reputation: 77796

I think you're a misleading yourself a bit.

Try out this approach

simple_class.lua

SimpleClass = {}
SimpleClass.__index = SimpleClass

function SimpleClass:new()
    local obj = {}
    setmetatable(obj, SimpleClass)
    obj.name = "yolo"
    return obj
end

example.lua

require "simple_class"

local instance = SimpleClass:new()

print(instance.name)
-- yolo

For more help, I'd check out this Simple Lua Classes from the Lua users wiki

Upvotes: 2

Related Questions