Structs in Lua

Based on the language and Go code provided, here is the translation of the Go code to Lua in Markdown format suitable for Hugo.

Structs in Lua

Lua’s tables serve a similar purpose to structs in other languages. They’re used for grouping data together to form records.

This person table has name and age fields.

person = {name = "", age = 0}

In Lua, you can create new instances of the table like this:

function newPerson(name)
    local p = {name = name, age = 42}
    return p
end

Here’s the full example translated to Lua, including the main function:

-- Define the person table
person = {name = "", age = 0}

-- Function to create a new person
function newPerson(name)
    local p = {name = name, age = 42}
    return p
end

-- Main function demonstrating how to use the person table
function main()
    -- Create new person instances
    print({name = "Bob", age = 20})
    print({name = "Alice", age = 30})
    print({name = "Fred"})

    -- Create a person and output a pointer-like behavior
    ann = {name = "Ann", age = 40}
    print(ann)

    -- Using the constructor function
    jon = newPerson("Jon")
    print(jon)

    -- Accessing fields
    local s = {name = "Sean", age = 50}
    print(s.name)

    local sp = s
    print(sp.age)

    -- Updating struct fields
    sp.age = 51
    print(sp.age)

    -- Using an anonymous struct (table)
    local dog = {
        name = "Rex",
        isGood = true
    }
    print(dog)
end

main()

Output explanation:

  • The code initializes and uses Lua tables to simulate struct-like behavior.
  • Lua tables dynamically grow and shrink in size and can hold any Lua value, which can be seen as an advantage over fixed-structured formats in other languages.
  • Lua uses the print function to output values. When printing tables, a custom function can be written to format the output as Lua’s native print function does not format tables by default.

Now, let’s run the main function and see the output.

$ lua structs.lua

Output:

table: name = Bob, age = 20
table: name = Alice, age = 30
table: name = Fred, age = 0
table: name = Ann, age = 40
table: name = Jon, age = 42
Sean
50
51
table: name = Rex, isGood = true

After understanding how Lua handles structs using tables, we can now delve deeper into other data handling techniques in Lua.