Objects

Object Initialization

To create a new object, use the new statement to instantiate a class:

local foo = {}

function foo:do_foo()
    print("Doing foo.")
end

-- Create a new instance
bar = foo:new()
bar:do_foo()

For a full discussion, see the Classes and Objects chapter.

Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was nil, the new instance will be empty. An array converts to an object with properties named by keys and corresponding values. Note that in this case before Lua 5.2 numeric keys have been inaccessible unless iterated.

local obj = setmetatable({}, {})
obj = {'1' = 'foo'}

Additional Resources

📚

Official Documentation

Access the complete Lua reference documentation with comprehensive examples and explanations.

Visit Documentation
🧩

Lua Libraries

Explore powerful libraries that extend Lua's functionality for various applications.

Browse Libraries
🎓

Tutorials

Step-by-step guides to help you master Lua programming from beginner to advanced levels.

Start Learning

Common Object Patterns

Here are some commonly used patterns when working with objects in Lua:

-- Simple class definition
local Person = {}
Person.__index = Person

function Person:new(name, age)
    local self = setmetatable({}, Person)
    self.name = name
    self.age = age
    return self
end

function Person:greet()
    print("Hello, my name is " .. self.name)
end

-- Create an instance
local john = Person:new("John", 30)
john:greet()  -- Outputs: Hello, my name is John