DEV Community

Kai
Kai

Posted on

Exploring Modding Systems: A Journey With Lua and Rust

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
Enter fullscreen mode Exit fullscreen mode

Next, add the rlua crate to your project:

cargo add rlua
Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Now, let’s add some flair to our Lua script by printing some information:

-- File: game/main.lua
print(_VERSION)
print("🌙 Lua is working!")
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
taikedz profile image
Tai Kedzierski

Nice and simple reminder, great.

Will you do a piece on exposing rust structs into lua and receiving lua tables back into rust ?