Joseph Fazekas
Joseph Fazekas

Reputation: 33

How do I reference an instance variable in lua?

function example()
    help = "no"
end

meme = example()

print(meme.help)

This code throws a run-time error. I don't know what to do.

I'm trying to teach myself lua and I know this can be done in java, but I can't get it working in lua.

Upvotes: 1

Views: 2128

Answers (2)

It is not very clear what you are trying to achieve, but from your question it seems that you want to emulate the object-oriented features of Java.

Keep in mind that Lua has no "instance variables" since it has no classes. Lua object oriented approach is uncommon and, unlike Java, is sort of prototype-based object orientation.

A very basic approach to creating an object with instance variables and methods is the following:

-- this is the "instance"
myobject = {}
-- this defines a new "instance variable" named `help`
myobject.help = "this is the help text"

-- this defines a getter method for the instance
-- the special name `self` indicates the instance
function myobject:GetHelp()
    return self.help
end

-- this defines a setter method for the instance
function myobject:SetHelp( help_text )
    self.help = help_text
end

print( myobject:GetHelp() )
myobject:SetHelp( "new help text" )
print( myobject:GetHelp() )

You can discover more about object orientation in Lua browsing the links in Lua WIKI's page about object oriented programming.

Upvotes: 0

AStopher
AStopher

Reputation: 4520

You're not returning in your function.

If the function doesn't return anything example() doesn't have a value, thus you're receiving a nil value error:

enter image description here

Using as the code is being returned, using help.meme will not work. As it is the only variable returned you can simply use this in your use case:

The below code will fix this:

function example()
    help = "no"
end

example()

print(help)

Upvotes: 1

Related Questions