Subscribe to Stuck in an Infiniteloop        RSS Feed
-----

Custom Recursive "Unpack" in Lua

Icon Leave Comment
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:

--[[
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
2345678
9101112131415
161718192021 22
23242526272829
3031     

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    20 user(s) viewing

    20 Guests
    0 member(s)
    0 anonymous member(s)