Rlua + Luarocks Modules -> Fail to load
solo-fox opened this issue · 3 comments
Hi Developers,
I will be fast and straightforward.
This is my rust code :
use rlua::{Lua, Result, Value};
fn main() -> Result<()> {
// Create a new Lua context
let lua = Lua::new();
// Load and execute the Lua script
lua.context(|lua_ctx| {
lua_ctx.load(
r#"
function run()
local result = 1 + 2
print("Result: " .. result)
return result
end
"#
)
.exec()?;
// Get the run function as a Lua Value
let result: Value = lua_ctx.globals().get("run")?;
// Check if the Lua value is a function and call it
if let Value::Function(func) = result {
let result: i64 = func.call(())?;
println!("Result in Rust: {}", result);
} else {
println!("Error: 'run' is not a function");
}
Ok(())
})
.map_err(|e| {
eprintln!("Error: {:?}", e);
e
})
}
And this what I get from rlua
Error: runtime error: [string "?"]:2: module 'lrand' not found: no field package.preload['lrand']
no file '/usr/local/share/lua/5.4/lrand.lua' no file '/usr/local/share/lua/5.4/lrand/init.lua' no file '/usr/local/lib/lua/5.4/lrand.lua' no file '/usr/local/lib/lua/5.4/lrand/init.lua' no file './lrand.lua'
no file './lrand/init.lua'
stack traceback: [C]: in ?
[C]: in function 'require'
[string "?"]:2: in main chunk
But when I ran luarocks list
, I get
luarocks list
Rocks installed for Lua 5.3
---------------------------
lrand
1.0.0-0 (installed) - /usr/local/lib/luarocks/rocks-5.3
Also lrand is installed but cannot be loaded from rlua!!! Can someone please help me finding the issue!
Thanks.
Hi,
It looks like you've configured rlua with the default "builtin-lua54", but are trying to use luarocks installed with Lua 5.3.
To use the system-installed Lua 5.3 library instead, specify the dependency liks this in Cargo.toml
:
rlua = { version = "0.19", default-features = false, features=["system-lua53"] }
Second, by default rlua
disables C extensions for safety. lrand
is a C extension so that needs enabling. Instead of Lua::new
, you can use Lua::unsafe_new_with_flags
:
let lua = unsafe { Lua::unsafe_new_with_flags(rlua::StdLib::ALL, rlua::InitFlags::NONE) };
Depending on your luarocks or Lua installations, you may also need to add the luarocks path to package.cpath
, but I didn't need to do that on my Ubuntu 22.04 system with luarocks installed from the Ubuntu package.
Putting it together, this worked for me: https://github.com/jugglerchris/rlua_luarocks_lrand
rlua_luarocks_lrand$ luarocks-5.3 list
Rocks installed for Lua 5.3
---------------------------
lrand
1.0.0-0 (installed) - /usr/local/lib/luarocks/rocks-5.3
rlua_luarocks_lrand$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/rlua_luarocks_lrand`
6708800777304496116
It is so good to get solutions from expertise rather than searching for days and trying ChatGPT capabilities.
Thanks, it solved the problem!
Glad to be able to help!