mlua-rs / mlua

High level Lua 5.4/5.3/5.2/5.1 (including LuaJIT) and Roblox Luau bindings to Rust with async/await support
Other
1.75k stars 139 forks source link

table.concat expect got "hello" #421

Closed cppcoffee closed 5 months ago

cppcoffee commented 5 months ago

Define UserData, access field to return an Vec<u8>, call table.concat expecting "hello", which outputs "104101108108111".

version and features:

[dependencies]
mlua = { version = "0.9.8", features = ["lua54", "vendored"] }

example:

struct Demo;

impl mlua::UserData for Demo {
    fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(fields: &mut F) {
        fields.add_field_method_get("field", |_, _this| Ok("hello".as_bytes().to_vec()));
    }
}

fn main() {
    let lua = mlua::Lua::new();

    let lua_demo_create = lua.create_function(lua_demo_create).unwrap();
    lua.globals().set("demo_create", lua_demo_create).unwrap();

    lua.load("local a = demo_create() print(type(a.field)) print(table.concat(a.field))")
        .exec()
        .unwrap();
}

fn lua_demo_create(_: &mlua::Lua, _: ()) -> mlua::Result<Demo> {
    Ok(Demo)
}

output:

% cargo run
table: 0x600002f3cec0
104101108108111

expect lua output:

% lua
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
> field={'h','e','l','l','o'}
> table.concat(field)
hello
cppcoffee commented 5 months ago

I'm sorry. It's my problem, code as follow:

            let chars = vec!['h', 'e', 'l', 'l', 'o'];
            let table = lua.create_table()?;
            for (i, &char) in chars.iter().enumerate() {
                table.set(i + 1, char.to_string())?;
            }
            Ok(table)
khvzak commented 5 months ago

I'm sorry. It's my problem, code as follow:

            let chars = vec!['h', 'e', 'l', 'l', 'o'];
            let table = lua.create_table()?;
            for (i, &char) in chars.iter().enumerate() {
                table.set(i + 1, char.to_string())?;
            }
            Ok(table)

Another version:

let table = lua.create_sequence_from("hello".split_terminator("").skip(1))?;