#ifndef LUA_HELPERS_H
#define LUA_HELPERS_H

#include <lauxlib.h>
#include <lua.h>
#include <raylib.h>

static Vector3 lua_readVector3(lua_State *L, int index)
{
	Vector3 v = { 0 };

	if (!lua_istable(L, index))
		return v;

	lua_getfield(L, index, "x");
	if (lua_isnumber(L, -1)) {
		v.x = lua_tonumber(L, -1);
		lua_pop(L, 1);

		lua_getfield(L, index, "y");
		v.y = luaL_optnumber(L, -1, 0);
		lua_pop(L, 1);

		lua_getfield(L, index, "z");
		v.z = luaL_optnumber(L, -1, 0);
		lua_pop(L, 1);

		return v;
	}
	lua_pop(L, 1);

	lua_rawgeti(L, index, 1);
	v.x = luaL_optnumber(L, -1, 0);
	lua_pop(L, 1);

	lua_rawgeti(L, index, 2);
	v.y = luaL_optnumber(L, -1, 0);
	lua_pop(L, 1);

	lua_rawgeti(L, index, 3);
	v.z = luaL_optnumber(L, -1, 0);
	lua_pop(L, 1);

	return v;
}

static Vector2 lua_readVector2(lua_State *L, int index)
{
	Vector2 v = { 0 };

	if (!lua_istable(L, index))
		return v;

	lua_getfield(L, index, "x");
	if (lua_isnumber(L, -1)) {
		v.x = lua_tonumber(L, -1);
		lua_pop(L, 1);

		lua_getfield(L, index, "y");
		v.y = luaL_optnumber(L, -1, 0);
		lua_pop(L, 1);

		return v;
	}
	lua_pop(L, 1);

	lua_rawgeti(L, index, 1);
	v.x = luaL_optnumber(L, -1, 0);
	lua_pop(L, 1);

	lua_rawgeti(L, index, 2);
	v.y = luaL_optnumber(L, -1, 0);
	lua_pop(L, 1);

	return v;
}

#endif // LUA_HELPERS_H
