Skip to content

2. Variables

Felice D'Angelo edited this page Jan 29, 2023 · 1 revision

Local variables

Local variables are defined in the same way as Lua:

local number = 1
local string = "hello!"
local bool = false
local x, y = 2.3, 5.8 //like in Lua multiple variables can be defined at once.

Table destructuring

To more easily extract all members of a table, Clue adds table destructuring:

local table = {a = 1, b = 2}
local {a, b} = table //to destructure a table simply wrap the variable names in {}

The above code will be compiled into:

local table = {
	a = 1, 
	b = 2
};
local _internal0 = table;
local a, b = _internal0.a, _internal0.b;

Table destructuring can only be done when defining new local or global variables

Global variables

While globals can be defined the same way it's done in Lua, Clue adds a global keyword:

global x = 3

This way it can be easier to remember which variables are globals.

If the version of Lua you're compiling to does not allow you to define globals using a metatable, the --rawsetglobals flag will make Clue call rawset when defining globals:

x = 3; --output without the flag enabled
rawset(_G, "x", 3); --output with the flag enabled

Static variables

Static variables work similar to global variables, but they are not inserted into _G (the global environment).

They can be useful when the Lua version you're using is slow with globals, does not allow them or you just don't want to pollute _G.

Note that due to the way Lua handles locals at file scope (yes statics are just that) you may not be able to define more than around 200 statics.

Since statics are locals at file scope, they will act like globals only inside Clue code (because every Clue file is merged into one).

static a, b, c;

Altering variables

Altering already defined variables works the same way as Lua, but Clue adds special operators to make some common operations easier:

a = 0
b += 1
c -= 2
d *= 3
e /= 4
f ^= 5
g ..= "6"
h %= 7
i &&= 8
j ||= 9
k ??= 10

This code would be converted to:

a = 0;
b = b + 1;
c = c - 2;
d = d * 3;
e = e / 4;
f = f ^ 5;
g = g .. "6";
h = h % 7;
i = i and 8;
j = j or 9;
if k == nil then
    k = 10;
end

Pseudo variables

The $ "variable" can only be used when altering other variables, it represents the variable we are currently altering:

local a = 3
a += $
print(a) //this will print 6

When altering more variables at once a number can be put after the $ to represents which variable it's referring to:

local a, b = "world!", "Hello "
a, b = $2, $1
print(a..b) //will print "Hello world!"

The first variable is $1 the second is $2 and it goes on until $9, $0 and $10 onwards are not valid pseudo variables

Clone this wiki locally