1

I'm trying to initialize a table of default properties for my script, and I'm facing the following scenario:

_property_table = {

    k1 = "val1",
    k2 = "val2",
    k3 = k1 .. "val3",

}

print(_property_table.k3)

When trying to concatenate k1 within the table constructor, lua fails with the following error:

_impl error: [string "main.lua"]:10: attempt to concatenate global 'k1' (a nil value)

Is this behavior expected, or am I missing something?

I'm fairly new to Lua, so any tips or suggestions on how to proceed would be appreciated.

Thanks

1 Answer 1

2

That behaviour is expected: k1 is not a variable name, k1 = is simply a shortcut for ["k1"] = inside a table expression. There are two basic solutions:

  1. Use a variable:

    local k1 = "val1"
    _property_table = {
        k1 = k1,
        k2 = "val2",
        k3 = k1 .. "val3",
    }
    
  2. Assign k3 after the table creation:

    _property_table = {
        k1 = "val1,
        k2 = "val2",
    }
    _property_table.k3 = _property_table.k1 .. "val3"
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I went on and followed the second approach you described.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.