I’ve been having a hard time with this and I’m not sure why it’s so difficult for me to understand.
Let’s say I have a shopping cart.
local cart = {
bananas = 2;
apples = 4;
}
Then let’s add the purse as well.
local cart = {
bananas = 2;
apples = 4;
purse = {
cash = 20;
debit = 100;
};
}
When I define the element within purse I get this nil from output, which confuses me?
print(table.find(cart.purse,2))
> nil
Or if I wanted to call the element specifically on its own it still calls nil.
print(table.find(cart.purse,"cash"))
> nil
What am I doing wrong here?
table.find only works on arrays, not dictionaries. Lua arrays are ordered, so a linear search algorithm is performed whereas this wouldn’t be possible with dictionaries that are unordered.
1 Like
sjr04
(uep)
January 20, 2021, 1:58am
#3
Would that really be necessary tho? If you index for something that doesn’t exist, nil
is returned.
local t = { a = 1 }
print(t.b) --> nil
1 Like
So if you don’t recommend this solution, what’s an alternative I can try?
Look at the above reply by @sjr04 . Simply check if cart.purse
exists and if so, check if cart.purse.cash
exists.
local foundCash = cart.purse and cart.purse.cash
--nil or cash value
1 Like
asgm
(asgm)
January 20, 2021, 2:09am
#6
To define the element within the purse, do
cart.purse.cash
If you want to call the element specifically on its own, do
_cashInPurse = cart.purse.cash
(This will error if purse is nil, but it won’t if cash is nil, it will just return nil)
1 Like