lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

           I am trying to use Light User Data to point to a 64 bit integer in my C module. I pass the address of the 64 bit integer as light user data back to lua. When Lua calls another function passing it the light user data then the value at the pointer is different. I have attached the code for the C module. And the run output from Lua:

-----C Module------
#include <lua.h>
#include <lauxlib.h>
#include <stdint.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
#include <compat-5.3.h>

void * cp;

static int
makeNew(lua_State *L) {
int64_t n;
    lua_Number d = lua_tonumber(L,1);
    n = (int64_t)d;
    printf("The number in function new is %lli\n",n);
void * p = (void *)&n;
cp = p;
printf("Pointer to the number is 0x%p\n",p);
printf("Value at the pointer is %lli\n",*(int64_t *)p);
printf("Value at creation pointer is %lli\n",*(int64_t *)cp);
return 1;

static int
tostring(lua_State *L) {
void * p = lua_touserdata(L,1);
printf("Pointer returned is 0x%p\n",p);
int64_t n = (*(int64_t *)p);
printf("Number at the pointer is %lli\n",n);
printf("Creation pointer is 0x%p\n",cp);
printf("Number at creation pointer is %lli\n",*(int64_t *)cp);
return 0;

luaopen_test(lua_State *L) {
lua_pushcfunction(L, makeNew);
lua_setfield(L, -2, "new");
lua_pushcfunction(L, tostring);
lua_setfield(L, -2, "tostring");
return 1;

--- Lua 5.1.5 Output -----
Lua 5.1.5  Copyright (C) 1994-2012, PUC-Rio
> test = require("test")
> a =^40)
The number in function new is 1099511627776
Pointer to the number is 0x000000000022F598
Value at the pointer is 1099511627776
Value at creation pointer is 1099511627776
> test.tostring(a)
Pointer returned is 0x000000000022F598
Number at the pointer is 2291096
Creation pointer is 0x000000000022F598
Number at creation pointer is 2291096

Please direct me to what I am doing wrong here.