lua-users home
lua-l archive

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




On Feb 13, 2020, at 10:48 AM, Lee Shallis <gb2985@gmail.com> wrote:

I'll start with an example of how the function is called:
handle:write(0xBADF00D,{0xC0,0xFF,0xEE})
Would this be the right way to extra each value in the second argument's table?
int lua_proc_change_data( lua_State *L ) {
proc_handle_t **handle = (proc_handle_t**)
luaL_checkudata(L,1,PROC_HANDLE_CLASS);
intptr_t addr = luaL_checkinteger(L,2);
intptr_t size, i;
uchar * array;
if ( !lua_istable(L,3) ) {
lua_pushinteger(L,0);
return 1;
}
size = lua_len(L,3);
if ( size < 1 ) {
lua_pushinteger(L,0);
return 1;
}
array = calloc( size, 1 );
for ( i = 0; i < size; ++i ) {
lua_pushinteger(L,i+1);
lua_gettable(L,3);
array[i] = lua_checkinteger(L,-1);
}
size = proc_change_data( NULL, *handle, addr, array, size );
free(array);
if ( size < 1 ) {
lua_pushinteger(L,0);
return 1;
}
lua_pushinteger(L,0);
return 1;
}

Couple of things…

— In the main “for” loop you are adding a stack item for each loop iteration… this will overflow the stack if “size” is big enough. You need to pop the integer off the stack after assign it to array[I].

— Although its unlikely to happen in the real-world, you should ALWAYS check that calloc() does not return NULL. If it does, your function will crash the app with a pointer exception.

— I dont know how critical performance is here, but allocating a C array dynamically for small blocks is pretty wasteful. If it were me I would have a small array available on the stack, and use that if “size” were small (say, 16 or less), only doing the alloc/free if size were above this threshold.

— You might want to look at the function lua_geti(), which is a cleaner way to get a table item using an C integer index (easier to use than lua_gettable().


—Tim