Still have questions? Join our Discord server and get real time help.
1

# I always get nil from this table, can you find my mistake?

Edited 6 days ago

Problem Solved, thanks for everyone who tried to help, but it was just me being absolutely blind.

0
print v.Name inside the for loop. That may help you figure out any problems you're having sheepposu 127 — 6d

1
gskw 450
6 days ago
Edited 6 days ago

To explain what's going on, I'll briefly explain how tables work in Lua.

Lua tables have two parts to them: a hash part and an array part. The array part contains the values of the table that are indexed using positive integers (1, 2, 3, etc.). The other part is the hash part, which can be indexed using any Lua value other than nil. Most commonly, strings are used for indexing it, but they could also be userdata or tables.

In your case, you're writing to the hash part of the table, but you're trying to find the values from the array part. v.Name is a string, so it goes the hash part, while keybinds[1] tries to index the array part. Instead, to check whether a table contains any values, including both the hash and array parts, you can use next, like so:

print(next(keybinds)) --> prints nil if and only if the table keybinds is empty


Side note: next is an iterator function, often used for going through tables in for loops. The two following loops are actually functionally equivalent!

    for i,v in pairs(KB:GetChildren()) do
keybinds[v.Name] = v.Value
end

do
local tab = KB:GetChildren()
local i, v = next(tab)
while i ~= nil do
keybinds[v.Name] = v.Value
end
end


Edit: Changed "numerical part" to "array part".

0
Thank you! I didn't know about how to use the next() function before. Really informative. noammao 225 — 6d
0
noammao 225
6 days ago

Could it be that on line 5, where you try to rename the children in the "keybinds" table it doesn't work because the keybinds table contains no children? I mean, it would make sense since you try to print the first child of the table but you never added any child into the table. Hence it returns nil. On line 5 You try to set the property of nothing to a string.

Maybe, I'm really not sure.