From 4e30eb1444fc88b73582db421d3a7467a3647064 Mon Sep 17 00:00:00 2001 From: Romain Forlot Date: Sat, 28 Jul 2018 11:57:35 +0200 Subject: New defaults useful functions on lua table Add a function that returns the size of a table as the operator '#' isn't considered are safe or accurate. Add another function to deep copy a table. Change-Id: Ia549315e305dd7d02b975a3e8a1278c4ab709eec Signed-off-by: Romain Forlot --- ctl-lib/ctl-lua-utils.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'ctl-lib') diff --git a/ctl-lib/ctl-lua-utils.c b/ctl-lib/ctl-lua-utils.c index 98dcebd..5c96226 100644 --- a/ctl-lib/ctl-lua-utils.c +++ b/ctl-lib/ctl-lua-utils.c @@ -86,6 +86,27 @@ function sleep(n)\n\ os.execute(\"sleep \" .. tonumber(n))\n\ end\n\ \n\ +function table_size(t)\n\ + local size = 0\n\ + for _ in pairs(t) do\n\ + size = size + 1\n\ + end\n\ + return size\n\ +end\n\ +function deep_copy(orig)\n\ + local orig_type = type(orig)\n\ + local copy\n\ + if orig_type == 'table' then\n\ + copy = {}\n\ + for orig_key, orig_value in next, orig, nil do\n\ + copy[deep_copy(orig_key)] = deep_copy(orig_value)\n\ + end\n\ + setmetatable(copy, deep_copy(getmetatable(orig)))\n\ + else -- number, string, boolean, etc\n\ + copy = orig\n\ + end\n\ + return copy\n\ +end\n\ function table_eq(table1, table2)\n\ local avoid_loops = {}\n\ local function recurse(t1, t2)\n\ -- cgit 1.2.3-korg