For the 3rd example, you do not want to reseed the random number generator every time you call it, especially if you are going to call it more than once within a single second. Can you figure out why?
Hint: Why does the following code seem to not work?
1
2
3
4
for i=1,100 do
	math.randomseed(os.time())
	print(math.random(100))
end
Variable number of arguments
1
2
3
4
5
6
7
function whoa(func, ...)
	local args = {...}
	for i,v in ipairs(args) do
		args[i] = func(v)
	end
	return args
end
Replacing an old function, but still using part of its old functionalities
1
2
3
4
5
local old_print = print
function print(text)
	old_print("Debug: In print")
	old_print(text)
end
Convert hexadecimal in a string to a number
1
tonumber("7f", 16) -- returns 127
Semi-regular expressions in searches
1
2
3
str = "12345555555555555567890"
str:find("5+") -- outputs 5,18, the first 5 starts at the 5th character, and ends at the 18th
str:sub(str:find("5+")) -- you can use this to actually see what string.find finds.
The : (colon) operator.
If you have a table T, then T:field() is equvalent to T.field(T)
Function calls with constants
You don't need parenthesis with function calls with a single argument that is either a constant table or string
1
2
print "Hello World"
table.sort {10,9,8,7,6,5,4,3,2,1}
The global table
1
2
3
4
5
6
for global_name in pairs(_G) do
	print(global_name)
end
_G["hello"] = "goodbye"
print(hello)
Functions that can "remember"
This is very useful for things like timers.
1
2
3
4
5
6
7
8
function square(x)
	return function()
		return x*x
	end
end
f = square(10)
print(f())
This can be extremely handy if you know how to use it correctly
"Persistent" functions
Coroutines can preserve states throught function calls.
1
2
3
4
5
6
7
8
9
10
11
counter = coroutine.wrap(function()
	local x = 1
	while true do
		coroutine.yield(x)
		x = x + 1
	end
end)
print(counter()) -- 1
print(counter()) -- 2
--etc
Adding libraries written in C (such as network) to CS2D
Say you put the dlls into the lib folder
1
package.cpath = package.cpath.."./lib/?.dll;../lib/?.dll;../../lib/?.dll;../../../lib/?.dll"
Copying a list
1
the_copy = {unpack(list)}
Printing out a list of strings
and most importantly
Metatables