DEV Community

Kai
Kai

Posted on

2 1 1 1 1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
taikedz profile image
TaiKedz

Nice and simple reminder, great.

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay