61 posts / categories / feed

Basic Lua Programming with Functions

Creating Functions in Lua

It is easier to create functions in Lua for reuse. One thing to note is that, usually for creating functions, we use to add function name(param) { }, but in Lua, do not add the parentheses, otherwise it will cause an error.

Creating Basic Function

-- hello world function
local function printMe()
    print("hello world);
end

-- calling the function
printMe();

Creating Function with Parameters

-- print function
local function printMe(content)
    print(content);
end

-- calling the function
printMe("haha");

There is no overloading in Lua like so in Java, hence it is not possible to use the same function name for even if one function requires a parameter, while the other doesn’t. Instead in using same function name will mean to override and replace the current function.

Define Local Variable to Anonymous Function

local printFn = function(title, content)
    print(title .. ": " .. content);
end

-- calling function
printFn("My Title", "Content Text");

Function with Multiple Arguments

It is possible to use “…” in your own defined functions, to get a lot of arguments, however you will need to verify the argument yourself.

local function lotsOfArgs(...)
    print(arg[1] .. " " .. arg[2]);
end

lotsOfArgs("Hello... ", "My Friend");

Using Functions in Tables, as Objects

This is useful especially for when you need to create things or split them up like helper functions, etc.

local table = {};
table.printMe = function(title, content)
    print(title .. ": " .. content);
end

table.sum = function(num1, num2)
    print(num1 + num2);
end

table.printMe("hehe", "haha");
table.sum(1, 3);