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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay