Is string passed to function by value or by reference?

If I have a long string (eg. 10 Kb), and I send it as a function argument, will it be passed as a value or reference (like a table)?

Pretty sure it would just be passed as a string, since it doesn’t really make sense for the string to be converted to a reference.

1 Like

Doing some more research, now directly in Lua, I confirmed that strings are passed by value and not by reference.

Does Lua pass by value or reference? – Quick-Advisors.com.

If the value is assigned to a variable and the variable is passed then the value is passed by reference. For literals, ‘nils’, ‘Booleans’, ‘numbers’ and ‘strings’ are passed by value whereas ‘tables’, ‘functions’, ‘threads’ and ‘userdatas’ are passed by reference.

print(nil) --nil (passed by value).
print(false) --false (passed by value).
print(1) --1 (passed by value).
print("Hello world!") --Hello world! (passed by value).
print({}) --table: memory address (passed by reference).
print(function() end) --function: memory address (passed by reference)
print(coroutine.create(function() end)) --thread: memory address (passed by reference).
print(newproxy()) --userdata: memory address (passed by reference).
2 Likes

Not true:

function a(s)
	s = 'x'
end

local b = 'abc'
a(b)
print(b) -- will print 'abc'
local function f(a) --'a' is a reference to the value of 's' not to 's' itself.
	print(a)
end

local s = "Hello world!" --'s' is a reference to a string literal.
f(s) --Pass 's' to 'f'.

Should have clarified but this is what I was referring to.

2 Likes