Making a cargo project and integrating Lua
Let’s embark on this journey by creating a new Cargo project and setting up a simple Lua script.
First, create a new Cargo project and navigate to the project directory:
cargo new modding-example && cd modding-example
Next, add the rlua
crate to your project:
cargo add rlua
Now, let’s create a main.rs
file with the following code to execute a Lua script:
// File: src/main.rs
use rlua::{Lua, Result};
use std::fs;
fn exec_lua_code() -> Result<()> {
let lua_code = fs::read_to_string("game/main.lua").expect("Unable to read the Lua script");
let lua = Lua::new();
lua.context(|lua_ctx| {
lua_ctx.load(&lua_code).exec()?;
Ok(())
})
}
fn main() -> Result<()> {
exec_lua_code()
}
If we try to run this, we’ll notice that the script can’t execute because the game/main.lua
file doesn't exist yet. Let's create the necessary directory and file:
mkdir game
touch game/main.lua
Now, let’s add some flair to our Lua script by printing some information:
-- File: game/main.lua
print(_VERSION)
print("🌙 Lua is working!")
With this setup, you should see the Lua version and the “Lua is working!” message printed to the console when you run your Rust program.
Top comments (1)
Nice and simple reminder, great.
Will you do a piece on exposing rust structs into lua and receiving lua tables back into rust ?