Skip to content

[Tutorial] References

Vurv edited this page Aug 8, 2021 · 2 revisions

If you are new to Lua you may be confused with how some variables behave in starfall.

Don't worry, I'll try to explain it in simple words :)

Disclaimer: I am not explaining how it works because its bit more complicated in lua, stuff I'll write there may be technically incorrect, but that's not the point - if you want technical explanation go to the Lua reference

What is referenced type? What's difference?

Usually when you assign something to variable it's being copied(For example in E2), that's not true in starfall for a lot of types.

Let's try this simple code:

local num = 5
local str = "Am I referenced?"
local tab = { text = "Are tables referenced?" }
local vec = Vector(10,10,10)

local temp

print("===== Number")
temp = num
temp = 10
print(num,"isn't",temp)

print("==== String")

temp = str
temp = "No"
print(str,temp)

print("=== Table")
temp = tab
temp.text = "Tables are referenced"

printTable(tab)
printTable(temp)

print("== Vector")
temp = vec
temp:setX(-10)
print(temp,vec)

Output should be:

===== Number
5	isn't	10
==== String
Am I referenced?	No
=== Table
text	=	Tables are referenced
text	=	Tables are referenced
== Vector
-10 10 10	-10 10 10

So as you can see number and string behave different way than table or vector, that's because number and string aren't referenced. Every time you assign string/number value is copied, however when you assign table, vector, angle, texture, hologram, entity, player, function(basically every complex type) instead of value you assign reference to it.

But... I dont want reference! I want to copy my vector/table/whatever!

That's really simple, you should use table.copy

What about other types?!

table.copy will work for most types in Starfall that's not true for LUA

But how do I do it exacly?

Simple code:

local vec1 = Vector(3,2,1)
local vec2 = table.copy(vec1)

Vec2 will have same x,y,z but wont be "connected" to vec1. It means that even when you change vec2 then vec1 won't change it's xyz.

I still dont get what's reference 😣

Okay, let's try to visualise it. Let's say you want to allow your friend to get color of your house. Would you rebuild identical house next to his one? No(at least if you want to make it fast), you would give him an address - that's what reference basically is. Instead of copying complex table each time you pass it as argument for function we just tell that function where our table is so it can access/modify it.

You mentioned functions, can they modify my object instead of returning it?

Yes! For example:

local mycar = {
 looksCool = false,
}
local function pimpMyCar(car)
  car.looksCool = true
end

print("Is my car cool?",mycar.looksCool)
pimpMyCar(mycar)
print("Is my car cool now?",mycar.looksCool)

As you can see, it's still same car, I didnt get new one( 😢 ).Instead my function made it look cooler! 😎