[Solved] Loading Lua C modules using rust-lua53

I am trying to use rust-lua53 as a standalone Lua interpreter that can do everything a regular Lua interpreter can do. rust-lua53 already bundles the source code for the Lua interpreter, and provides some bindings on top of it.

I am trying to use rust-lua53 to load a program like below, which loads a regular Lua module (serpent) and a Lua C module (lfs).

    print('hello')

    if not pcall(function() require('serpent') end) then
      print('error loading serpent')
    else
        local spt = require('serpent')
        print('serpent successfully loaded')
    end

    local status, err = pcall(function() require('lfs') end)
    print(err)

The regular module (serpent) loads fine, but the Lua C module gives errors. I suspect it is due to some incorrect linking which leads to some symbols not being available.

Here is my Rust program (which contains the Lua code above):

extern crate lua;

fn main() {
  let mut state = lua::State::new();
    state.open_libs();
    state.do_string("
    print('hello')

    if not pcall(function() require('serpent') end) then
      print('error loading serpent')
    else
        local spt = require('serpent')
        print('serpent successfully loaded')
    end

    local status, err = pcall(function() require('lfs') end)
    print(err)


    ");
}

The error it gives is as below:

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/rlua`
hello
serpent successfully loaded
error loading module 'lfs' from file '/home/deepak/lua53/lib/lua/5.3/lfs.so':
        /home/deepak/lua53/lib/lua/5.3/lfs.so: undefined symbol: lua_gettop

$ nm target/debug/rlua | grep lua_gettop
000000000000dd63 T lua_gettop

The symbol seems to exist in the executable, but somehow the code does not detect it. Any ideas what I can try to fix this problem?

After doing a little bit more research, it seems that I need to link the Rust program I have in a certain way to be able to export all the symbols correctly.

I put this in my .cargo/config

[build]
rustflags = ["-C", "link-args=-rdynamic"]

Discovered this via a tip here: Expose symbols to dynamic linker when linking with native library in Rust - Stack Overflow

Some more information in this blog post: Exploring LLVM/Clang Compiler Options | keitaito