Is there any way to pass primitive values by reference?

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)

1 Like

Nope, see the Lua 5.1 Reference Manual :

Tables, functions, threads, and (full) userdata values are objects : variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy.

Also see this stackoverflow discussion: Function/variable scope (pass by value or reference?) - Stack Overflow

3 Likes

In Lua, no I don’t believe so. Do you have a specific use case for this?

I mean, this would be more practical for typical use:

local myBoolean = false

local function Switch()
myBoolean = not myBoolean
end
1 Like

I see. So definitely no way of doing that. (perhaps when I’m more fluent in C I can modify the Lua source to have that behavior)

Not really, as I said, more of a curiosity question. Just’d be officially cool if it was doable. These would be essentially the same effort to write:

local isBehindObstacle, isInDistance, isInFOV = checkBehindObstacle(), checkDistance(), checkFOV()

local isBehindObstacle, isInDistance, isInFOV
checkBehindObstacle(isBehindObstacle)
checkDistance(isInDistance)
checkFOV(isInFOV)

Thanks to both of ya!

1 Like