Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/meta_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,21 @@ pub fn index<'gc>(
key: Value<'gc>,
) -> Result<MetaResult<'gc, 2>, MetaOperatorError> {
let idx = match table {
// In PUC-Lua, all strings are given the same metatable with an __index
// that points to the global string table. Here, we do the same thing of
// looking up indexes in the global string table, but without actually
// defining a metatable. This means it is not 100% compatible since it
// is possible to write cursed Lua which modifies this special
// metatable, but it is compatible enough that it works for the most
// common case of calling string methods in an OOP style.
Value::String(_) => {
let metatable = ctx
.get_global::<Table<'_>>("string")
.map_err(|_| MetaOperatorError::IndexKeyError(InvalidTableKey::IsNil))?;
let v = metatable.get_value(ctx, key);

return Ok(MetaResult::Value(v));
}
Value::Table(table) => {
let v = table.get_value(ctx, key);
if !v.is_nil() {
Expand Down
13 changes: 13 additions & 0 deletions tests/scripts/string.lua
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,16 @@ do
assert(is_err(function() return string.char(256) end))
assert(is_err(function() return string.char(-1) end))
end

do
local p = "hello"
assert(p:len("lo") == 5)

string.world = function(s)
return s .. " world"
end

assert(p:world() == "hello world")
assert(p[0] == nil)
assert(p["len"] == string.len)
end