Does this solve the string __index problem?

51 views
Skip to first unread message

Steven

unread,
Aug 19, 2025, 8:44:09 PMAug 19
to lua-l
Hi all. I remember reading somewhere recently that Roberto said that the string metatable's __index can't be for bytes because it's already in use for methods, so that you'd have to choose to have foo[2] or foo:gsub(...). If that's true, then why not just combine both behaviors into the existing metamethod? If argument is number, call string.byte or utf8.codepoint depending on a new config.h flag. Otherwise look it up in the given table. Would this not be a good solution?

Scott Morgan

unread,
Aug 19, 2025, 10:20:59 PMAug 19
to lu...@googlegroups.com
Pretty easy to implement Lua side:

getmetatable("").__index = function(s,k)
if type(k) == "number" then return string.byte(s, k); end
return string[k]
end

Not sure how wise it would be having the behaviour change on a compile
time flag. Would make portable code hard to write if you can't rely on a
specific behaviour. Much better to leave it up to the app/script.

Scott

Sainan

unread,
Aug 19, 2025, 10:43:01 PMAug 19
to lu...@googlegroups.com
We do something similar in Pluto, but instead the check for a number is done in C/the VM. But if you wanna be pedantic you could point out that this is a compatibility break for code like this:

string[1] = "one"
print(("a")[1]) -- "one" in Lua, "a" in Pluto

-- Sainan
Reply all
Reply to author
Forward
0 new messages