Open Frityet opened 2 months ago
Furthermore, as an extension, maybe full properties could be introduced?
local record MyRecord
x<get=get_x, set=set_x>: integer
end
function MyRecord:get_x(): integer
return 42
end
function MyRecord:set_x(val: integer)
print("setting x to "..val)
end
local tbl: MyRecord = ...
print(tbl.x) --42
tbl.x = 1 -- setting x to 1
which would turn into
local MyRecord = {}
function MyRecord:get_x()
return 42
end
function MyRecord:set_x(val)
print("setting x to "..val)
end
local tbl: MyRecord = ...
print(tbl:get_x())
tbl:set_x(1)
I am not a fan of full on properties. I don't like it when things that appear to be simply reading/writing to fields suddenly start to execute (potentially costly) functions.
Already have had plenty of times when things where much slower than expected because function calls where hiding in the code, pretending to be field accesses.
I do really like being able to say if a field is read-only though, and maybe set only as well.
Already have had plenty of times when things where much slower than expected because function calls where hiding in the code, pretending to be field accesses.
For better or worse, that is already a thing in Lua, because of metamethods.
I don't discount adding readonly fields in the future, though it can get either more complicated or less safe than what it seems initially, because of aliasing. One only needs to look at the constness rules from C and C++ to see that this can open quite a rabbit hole if one's not careful.
Having said that, I'm much less likely to add properties. The use-case suggested here sounds like a task for something like a compile-time metamethod (which is a more general concept than getter/setter properties). That would be more appealing to me, but I have no immediate plans to work on that either.
The use-case suggested here sounds like a task for something like a compile-time metamethod (which is a more general concept than getter/setter properties). That would be more appealing to me, but I have no immediate plans to work on that either.
Update: Teal '24 has some progress in that direction, but the __index
metamethod cannot be macro-expanded currently. Even if it could, it would not provide an easy way to implement getter/setter properties, so I don't have plans to focus on that right now.
awesome! thanks
Some lua libraries have tables which have fields that can be read from, but not written to:
Perhaps syntax such as
Could be introduced?