edubart / nelua-lang

Minimal, efficient, statically-typed and meta-programmable systems programming language heavily inspired by Lua, which compiles to C and native code.
https://nelua.io
MIT License
2.08k stars 68 forks source link

__newindex #205

Open IcedQuinn opened 1 year ago

IcedQuinn commented 1 year ago

The following test code results in invalid C code being generated:

local Farce = @record{
}
function Farce:__index(x: auto)
  return 0
end

local bleb: Farce
print(bleb["snert"])
bleb["snert"] = 32
/home/icedquinn/.cache/nelua/bruh.c:118:74: error: lvalue required as left operand of assignment
  118 |   bruh_Farce___index_1((&bruh_butt), ((nlstring){(uint8_t*)"snert", 5})) = 32;

There should be a corresponding __newindex for index assignment to go with __index.

This was tested against revision 5fea73365d40d49039025b948e2e231f8fc6b40d

edubart commented 1 year ago

Support for __newindex has yet to be added, when it's added this error should be fixed. But I could make this at least a compile error for now.

You can use __atindex to overcome this, however you have to integer a reference, so I understand that this is not exact replacement for __newindex and __index, but one advantage is that you need to implement only one method, here is an example with __atindex:

local Farce = @record{x: integer}
function Farce:__atindex(x: auto): *integer
  return &self.x
end

local bleb: Farce
print(bleb["snert"])
bleb["snert"] = 32
IcedQuinn commented 1 year ago

But this I could make this at least a compile error for now.

Yes. It definitely should not emit invalid C lol.

__atindex

I don't understand what is going on with this one. Its returning the reference to the call site which is then modifying it?

In Nim all of our operators are just syntactic sugar. []= has a signature []=(key: type; new_value: type) and it seems like Lua does something similar with the assignment syntax becoming a call to __newindex. But I'm not familiar with this codebase so I don't know how difficult patching it in would be.