From 930bc91359dd88166fe836a92bb4f34fa21497c6 Mon Sep 17 00:00:00 2001 From: dmiller Date: Mon, 6 May 2013 18:39:54 +0000 Subject: [PATCH] Modify stdnse.output_table to handle empty values better Two changes here, both minor. First, explicitly assigning a new key to nil does not add the key to the ordered set of keys. This better emulates the behavior of regular tables. > o = stdnse.output_table() > o["test"] = nil This previously resulted in output like this: |_ test: nil Now it simply omits the "test:" key. Second, I needed a way to tell whether an output table was empty or not. Since Lua's next() function doesn't call the __pairs metamethod, it was always returning nil. Instead, I used the __call metamethod, since it had the least preexisting semantic meaning: > o = stdnse.output_table() > =o() false > o["test"] = 1 > =o() true --- nselib/stdnse.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/nselib/stdnse.lua b/nselib/stdnse.lua index 6b9f5e73c..e3f92b1d7 100644 --- a/nselib/stdnse.lua +++ b/nselib/stdnse.lua @@ -18,6 +18,7 @@ local error = error; local getmetatable = getmetatable; local ipairs = ipairs local pairs = pairs +local next = next local rawset = rawset local require = require; local select = select @@ -1131,7 +1132,7 @@ function output_table () end local mt = { __newindex = function (_, k, v) - if t[k] == nil then + if t[k] == nil and v ~= nil then -- New key? table.insert(order, k) elseif v == nil then @@ -1151,6 +1152,9 @@ function output_table () __pairs = function (_) return coroutine.wrap(iterator) end, + __call = function (_) -- hack to mean "not_empty?" + return not not next(order) + end } return setmetatable({}, mt) end