# Linking to C librarys in lua

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

## 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)

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.so linking.o I get 5.954010 every time I run the program. Does anyone reconize what I'm doing wrong? Thanks in advance

##### 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 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 on other sites
Ahh, it seems I was wrong to think it'd work like some other languages. Thanks for your help, I know where to look now.