Just a quick snippet to tide you over until the next Lua tutorial.
The default unpack() function is written in C. So let's write our own (why? for fun of course!) in Lua. We'll take a recursive approach and use a neat default value feature:
Arguably the most important item in here is the i = i or 1 line. In English it says: If i has no value (nil) assign it to 1. Don't confuse this with an if structure, because it isn't. If we only call the function with one argument (like in the example) then 'i' will default to 1 (the first array index in Lua). The other important item here is the recursive call:
The if statement checks to make sure the table's value at 'i' is not nil (remember only nil and false equate to "false" in Lua, everything else is true, even zero).
Happy Coding!
--KYA
The default unpack() function is written in C. So let's write our own (why? for fun of course!) in Lua. We'll take a recursive approach and use a neat default value feature:
--[[
Custom unpack function
"unpacks" the table, returns its value and calls unpack again,
repeats until last non nil element
--]]
function unpack (t, i)
i = i or 1 --single argument (like below), i defaults to 1
if t[i] then
return t[i], unpack(t, i+1) --recursion
end
end
--example usage
table = {10,"Bob", 60}
print(unpack(table))
--output - 10 Bob 60
Arguably the most important item in here is the i = i or 1 line. In English it says: If i has no value (nil) assign it to 1. Don't confuse this with an if structure, because it isn't. If we only call the function with one argument (like in the example) then 'i' will default to 1 (the first array index in Lua). The other important item here is the recursive call:
if t[i] then return t[i], unpack(t, i+1) --call again
The if statement checks to make sure the table's value at 'i' is not nil (remember only nil and false equate to "false" in Lua, everything else is true, even zero).
Happy Coding!
--KYA
0 Comments On This Entry
← January 2022 →
| S | M | T | W | T | F | S |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | 31 |
Tags
My Blog Links
Recent Entries
Recent Comments
Search My Blog
19 user(s) viewing
19 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)



Leave Comment









|