Advertisement Jump to content
Sign in to follow this  
Fibonacci One

Linking to C librarys in lua

This topic is 5206 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I'm trying to learn how to write a function in C, compiling/linking it as a shared object, then calling said function in Lua. I can get it to work just fine if I do not pass any parameters into the C function, but as soon as I try to send something I get some weird results. here are some code samples: I use --> to indicate what the output of a statement is in lua
// In the C file (linking.c)
void hw(double temp)
    printf("Hello %f.\n", temp);

// in the lua file (linking.lua)
hello = loadlib("/usr/LUAcode/linking/", "hw")

print(hello) -->function: 0x806a318
hello(1.0) --> Hello 5.954010
hello(3.14159265) -->Hello 5.954010

The commands I use to compile Linking.c are: gcc -fPIC -c linking.c ld -shared -o linking.o I get 5.954010 every time I run the program. Does anyone reconize what I'm doing wrong? Thanks in advance

Share this post

Link to post
Share on other sites
Yes. Hello function is called like a standard Lua function, so the first and the only argument must be a Lua state. It gives you the pointer to the state, but you treat it as a float!

The best thing here would be to read Lua manual, describing exact rules for exporting C functions. The function returned by dynamic library loader is supposed to open your shared library - the C code of it should register all the functions your library has.

Share this post

Link to post
Share on other sites
I'm not sure how that is even working.

In order to call a C function from lua it needs to return a const int and accept a lua state as a parameter.

The parameters to the function call get pushed onto the stack, and you must remove them from the stack to get them.

Return values get pushed back onto the stack, the return being the number of variables being returned.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!