Merge branch 'master' of git://github.com/BTAxis/naev into testmission
[naev.git] / src / nlua_time.c
blob892e9d9efb1ac13053da86f0a354f8d78d45269e
1 /*
2 * See Licensing and Copyright notice in naev.h
3 */
5 /**
6 * @file nlua_time.c
8 * @brief Time manipulation Lua bindings.
9 */
11 #include "nlua_time.h"
13 #include "naev.h"
15 #include <stdlib.h>
17 #include "lauxlib.h"
19 #include "nlua.h"
20 #include "nluadef.h"
21 #include "log.h"
22 #include "ntime.h"
25 /* time */
26 static int time_get( lua_State *L );
27 static int time_str( lua_State *L );
28 static int time_units( lua_State *L );
29 static const luaL_reg time_methods[] = {
30 { "get", time_get },
31 { "str", time_str },
32 { "units", time_units },
33 {0,0}
34 }; /**< Time Lua methods. */
37 /**
38 * @brief Loads the Time Lua library.
40 * @param L Lua state.
41 * @param readonly Whether to open it as read only.
42 * @return 0 on success.
44 int nlua_loadTime( lua_State *L, int readonly )
46 (void)readonly;
47 luaL_register(L, "time", time_methods);
48 return 0;
52 /**
53 * @brief Bindings for interacting with the time.
55 * Usage is generally something as follows:
56 * @code
57 * time_limit = time.get() + time.units(15)
58 * player.msg( string.format("You only have %s left!", time.str(time.get() - time_limit)) )
60 * -- Do stuff here
62 * if time.get() > time_limit then
63 * -- Limit is up
64 * end
65 * @endcode
67 * @luamod time
69 /**
70 * @brief Gets the current time in internal representation time.
72 * @usage t = time.get()
74 * @luareturn Time in internal representation time.
75 * @luafunc get()
77 static int time_get( lua_State *L )
79 lua_pushnumber( L, ntime_get() );
80 return 1;
82 /**
83 * @brief Converts the time to a pretty human readable format.
85 * @usage strt = time.str()
86 * @usage strt = time.str( time.get() + time.units(5) )
88 * @luaparam t Time to convert to pretty format. If ommitted, current time is
89 * used.
90 * @luareturn The time in human readable format.
91 * @luafunc str( t )
93 static int time_str( lua_State *L )
95 char *nt;
96 if ((lua_gettop(L) > 0) && (lua_isnumber(L,1)))
97 nt = ntime_pretty( (unsigned int) lua_tonumber(L,1) );
98 else
99 nt = ntime_pretty( ntime_get() );
100 lua_pushstring(L, nt);
101 free(nt);
102 return 1;
105 * @brief Converts stu to internal representation time.
107 * @usage time_limit = time.get() + time.units(5)
109 * @luaparam stu Time in stu to convert to internal representation time. If
110 * ommitted, 1 stu is used.
111 * @luareturn The value of stu in internal representation time.
112 * @luafunc units( stu )
114 static int time_units( lua_State *L )
116 if ((lua_gettop(L) > 0) && (lua_isnumber(L,1)))
117 lua_pushnumber( L, (unsigned int)lua_tonumber(L,1) * NTIME_UNIT_LENGTH );
118 else
119 lua_pushnumber( L, NTIME_UNIT_LENGTH );
120 return 1;