Add support for action function
[minetest_sfinv_buttons.git] / init.lua
blob2db45d2df4caef7260121df339705836313e1007
1 -- Boilerplate to support localized strings if intllib mod is installed.
2 local S
3 if minetest.get_modpath("intllib") then
4 S = intllib.Getter()
5 else
6 S = function(s) return s end
7 end
9 local buttons = {}
10 local buttons_num = 0
12 local button_prefix = "sfinv_button_"
14 sfinv_buttons = {}
17 sfinv_buttons.register_button = function(name, def)
18 buttons[name] = def
19 buttons_num = buttons_num + 1
20 end
22 sfinv.register_page("sfinv_buttons:buttons", {
23 title = S("More"),
24 is_in_nav = function(self, player, context)
25 return buttons_num > 0
26 end,
27 get = function(self, player, context)
28 local f = ""
29 local y = 0
30 for name, def in pairs(buttons) do
31 if def.image ~= nil then
32 f = f .. "image[0.1,"..(y+0.1)..";0.8,0.8;"..def.image.."]"
33 end
34 f = f .. "button["..
35 "1,"..y..";3,1;"..
36 button_prefix..minetest.formspec_escape(name)..";"..
37 minetest.formspec_escape(def.title)..
38 "]"
39 y = y + 1
40 end
41 return sfinv.make_formspec(player, context, f)
42 end,
43 on_player_receive_fields = function(self, player, context, fields)
44 for widget_name, _ in pairs(fields) do
45 local id = string.sub(widget_name, string.len(button_prefix) + 1, -1)
46 if buttons[id] ~= nil and buttons[id].action ~= nil then
47 buttons[id].action(player)
48 end
49 end
50 end,
53 -- Test
54 sfinv_buttons.register_button("button1", { title = "Button 1" })
55 sfinv_buttons.register_button("button2", { title = "Button 2" })
56 sfinv_buttons.register_button("button3", { title = "Button 3" })
57 sfinv_buttons.register_button("button4", { title = "Button 4" })