Do you use any form of JS Symbols? (in lua)

https://javascript.info/symbol

When I was learning a little bit of javascript I came across their Symbol type and I thought it was really cool
Lua doesn’t have any innate symbol type, but I was wondering if you guys still used anything similar?

Maybe you could treat private variables (prefixed with ‘_’) as symbols, but do you take it a step further?
E.g: newproxy() symbols inside of tables; or, have a separate module that stores the symbols of individual tables you have-but then no __index inheritance?

I think a lot of things would have been nicer if symbols had been implemented (such as metamethods being symbols), but what are your thoughts?

1 Like

Seems like this could easily be implemented using only tables; they meet all of the same criteria short of a global storage and skipped in for loops. This doesn’t seem like a type that would ever really be useful in Lua.

I think their use case comes in the convenience of them being skipped by iterators and accessible only if you have a reference to them

If your object inherits from multiple classes that are independent and unaware of each other (not really oop, but I like this; there’s probably some fancier terminology), it would be nice to not worry that one’s data might be incorrectly manipulated by another class etc

This can be achieved by writing a custom iterator.

local function iterator(tab, idx)
	local key = idx
	local value

	repeat
		key, value = next(tab, key)
	until type(key) ~= 'table' or not rawget(key, 'is_symbol')

	return key, value
end

local function no_symbols(tab)
	return iterator, tab, nil
end

image

1 Like

It is tedious to always use your own custom iterators instead of the built in ones though
But I’m not doubting its possibility, I’m just wondering if you actually use something like this

Off topic, but what is that programming software?
The terminal looks like visual studio code am I right?

This is how Roblox internally creates symbols in Lua:

3 Likes

What do they use them for? Is there anything outside of the roact library?

They’re used wherever they need a special marker as a key. In Roact, it’s used as a stand-in for nil when setting state (because :setState({ foo = nil }) wouldn’t have the key foo be iterated over). Another example that comes to mind is in Lemur, the typeKey symbol is used for the emulated typeof function to work.

1 Like