2009-05-16 Pavel Roskin <proski@gnu.org>
[grub2/bean.git] / script / lua / grub_lib.c
blob0295f0dccdbe298d96660b3d3e73e5f905ce4d59
1 /*
2 * GRUB -- GRand Unified Bootloader
3 * Copyright (C) 2009 Free Software Foundation, Inc.
5 * GRUB is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * GRUB is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
19 #include "lua.h"
20 #include "lauxlib.h"
21 #include "lualib.h"
22 #include "grub_lib.h"
24 #include <grub/env.h>
25 #include <grub/parser.h>
26 #include <grub/command.h>
28 static int
29 grub_lua_run (lua_State *state)
31 int n;
32 char **args;
33 grub_err_t result;
35 if (! lua_gettop(state))
36 return 0;
38 if ((! grub_parser_split_cmdline (lua_tostring (state, 1), 0, &n, &args))
39 && (n >= 0))
41 grub_command_t cmd;
43 cmd = grub_command_find (args[0]);
44 if (cmd)
45 (cmd->func) (cmd, n, &args[1]);
46 else
47 grub_error (GRUB_ERR_FILE_NOT_FOUND, "command not found");
49 grub_free (args[0]);
50 grub_free (args);
53 result = grub_errno;
54 grub_errno = 0;
56 lua_pushinteger(state, result);
58 if (result)
59 lua_pushstring (state, grub_errmsg);
61 return (result) ? 2 : 1;
64 static int
65 grub_lua_getenv (lua_State *state)
67 int n, i;
69 n = lua_gettop(state);
70 for (i = 1; i <= n; i++)
72 const char *name, *value;
74 name = lua_tostring (state, i);
75 value = grub_env_get (name);
76 if (value)
77 lua_pushstring (state, value);
78 else
79 lua_pushnil (state);
82 return n;
85 static int
86 grub_lua_setenv (lua_State *state)
88 const char *name, *value;
90 if (lua_gettop(state) != 2)
91 return 0;
93 name = lua_tostring (state, 1);
94 value = lua_tostring (state, 2);
96 if (name[0])
97 grub_env_set (name, value);
99 return 0;
102 luaL_Reg grub_lua_lib[] =
104 {"run", grub_lua_run},
105 {"getenv", grub_lua_getenv},
106 {"setenv", grub_lua_setenv},
107 {0, 0}