Table i problem

local t = {}

table.insert(t,“Apple”)

print(t[1]) – Apple

–// the problem:

t[“Default”] = “Coconut” – it’s going to be placed at end of table, the second place right?
print(t[2]) – nil

is where any ways i can get the second place of table ?

1 Like

You’re setting the “Default” key of t to “Coconut”, so it won’t be accessible through t[2]. It will be accessible through t["Default"] or t.Default.

When you make a table like this:

local t = {
    "foo",
    "bar"
}

Lua treats it like this:

local t = {
    [1] = "foo",
    [2] = "bar"
}

so if we add “Default” to that, it will look like this:

local t = {
    [1] = "foo",
    [2] = "bar",
    ["Default"] = "Coconut"
}

print(t[3]) --> nil because there is no key 3 within table "t"




To get the second place of a table with the key “Default”, you can modify some metamethods, but also note that non-numerical keys are not sorted so it may come out as different results each time.

2 Likes

thank you for your help have a good day / night!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.