Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare variables with a type in Lua

Is it possible to create variables to be a specific type in Lua?

E.g. int x = 4

If this is not possible, is there at least some way to have a fake "type" shown before the variable so that anyone reading the code will know what type the variable is supposed to be?

E.g. function addInt(int x=4, int y=5), but x/y could still be any type of variable? I find it much easier to type the variable's type before it rather than putting a comment at above the function to let any readers know what type of variable it is supposed to be.

The sole reason I'm asking isn't to limit the variable to a specific data type, but simply to have the ability to put a data type before the variable, whether it does anything or not, to let the reader know what type of variable that it is supposed to be without getting an error.

like image 703
Drew Avatar asked Dec 12 '13 21:12

Drew


1 Answers

You can do this using comments:

local x = 4 -- int

function addInt(x --[[int]],
                y --[[int]] )

You can make the syntax a = int(5) from your other comment work using the following:

function int(a) return a end
function string(a) return a end
function dictionary(a) return a end

a = int(5)
b = string "hello, world!"
c = dictionary({foo = "hey"})

Still, this doesn't really offer any benefits over a comment.

like image 51
bames53 Avatar answered Oct 03 '22 14:10

bames53