musiclight2/lua_utils.c

74 righe
1.7 KiB
C

/*
* vim: sw=2 ts=2 expandtab
*
* THE PIZZA-WARE LICENSE" (derived from "THE BEER-WARE LICENCE"):
* <cfr34k@tkolb.de> wrote this file. As long as you retain this notice you can
* do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a pizza in return. - Thomas Kolb
*/
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include "lua_utils.h"
void lua_showerror(lua_State *L, const char *msg) {
fprintf(stderr, "\nLUA ERROR:\n %s: %s\n\n",
msg, lua_tostring(L, -1));
}
void lua_pushdoublearray(lua_State *L, double *numbers, size_t len) {
size_t i;
// create an empty table
lua_createtable(L, len, 0);
for(i = 0; i < len; i++) {
// push key and value
lua_pushnumber(L, i+1); // lua arrays count from 1
lua_pushnumber(L, numbers[i]);
// store the values in the table
lua_settable(L, -3);
}
}
void lua_pushsamplearray(lua_State *L, sample *numbers, size_t len) {
size_t i;
// create an empty table
lua_createtable(L, len, 0);
for(i = 0; i < len; i++) {
// push key and value
lua_pushnumber(L, i+1); // lua arrays count from 1
lua_pushnumber(L, numbers[i]);
// store the values in the table
lua_settable(L, -3);
}
}
void lua_readdoublearray(lua_State *L, double *numbers, size_t len) {
size_t k;
double v;
// go to the top of the stack
lua_pushnil(L);
while(lua_next(L, -2)) {
v = lua_tonumber(L, -1);
lua_pop(L, 1);
k = lua_tointeger(L, -1);
if(k > len || k < 1) {
fprintf(stderr, "Warning: Lua index (%u) is out of C array range (%u)!\n", k, len);
} else {
numbers[k-1] = v;
}
}
lua_pop(L, 1);
}