Hello!
So I’ve been programming a lot of C recently, and I got addicted to functions passing by reference to change a value. Now I want to know if there is actually a way to do it in Lua!
Problem is: I want to pass a boolean (primitive) to the function, but IIRC, only values passed by reference are userdatas, threads, functions and tables.
Here’s how I want it to work:
local function isNumberEven(num: number, result: boolean)
result = (num% 2 == 0)
end
local isEven: boolean
isNumberEven(2, isEven)
print(isEven) --> true
(how it’d look in C, for context)
#include<stdio.h>
// C has this special operator called "address-of" and it gets the memory adress of the value
void isNumberEven(int num, bool &result) {
// Thus, this will change the value in the memory address, not just the variable
result = (num % 2 == 0);
}
int main() {
bool isEven;
isNumberEven(2, isEven);
printf("%s", (isEven == 1 ? "True" : "False")); // --> True
}
What I tried is to have a table with all the results, and in fact it works since tables are passed as a reference:
type ResultTable = { [number] : boolean?}
local function isNumberEven(num: number, resultTable: ResultTable)
table.insert(resultTable, (num % 2 == 0))
end
local resultTable: ResultTable = {}
isNumberEven(2, resultTable)
print(resultTable[#resultTable]) --> true
However, I believe I don’t need to say how unpractical this is, and the table is also going to occupy memory if not handled properly, which adds even more unnecessary work.
So here’s the question again, is there any way to pass primitive values by reference?
(this is actually more of a curiosity question, so please don’t say that this isn’t C 'n stuff like that)