1
2
3
4
5
6
7
8
9
--a function that expects a table
function func(tbl) end
--when passing a table into the function, the table isn't passed,
--but the memory address of where the table is:
--this will create a table somewhere in memory and pass the address to the function
func({1,2,3})
--what the function gets is something like (0x1ac1230)
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
32
33
34
35
36
37
38
39
40
41
function array(size, value)
	--the "value" parameter gets the value passed
	--in this case {0, 0, 0, 0, 0}
	--thus it will be the same as defining and initializing it here:
	--local value = {0, 0, 0, 0, 0}
	local out = {}
	
	
	for i = 1, size do
		--goes through each element and assign the value for them.
		--if the value happens to be a table, then the memory address of "value"
		-- is passed onto it which will be the same for every element because it's
		out[i] = value
	end
	return out
end
--step for step:
array(5, array(5, 0))
-- 1. call the array function and pass on the arguments (first call to "array")
-- 2. when it gets to the "value" parameter, it will call array(5,0)
-- 3. array(5,0) gets called -> returns {0, 0, 0, 0, 0} (second call to "array")
-- 4. the value parameter gets assigned {0, 0, 0, 0, 0} somewhere in memory,
--let's say at memory (0x1ac1230).
-- 5. create a table to return (let's call it "out")
-- 6. loop through "size" amount of times
-- 7. for each element; point the element to the memory address of "value".
-- 8 return the table
--Total calls to "array" - 2
--Total created tables - 2
--array(5, array(5,0)) would be the same as:
local inner_array = array(5, 0)
array(5, inner_array)
--as you can see inner_array is passed onto array function as a reference or shallow copied
--thus all the elements would share the same memory address as inner_array