[NTG-context] lpdf.checkedkey has problem with false values

Michail Vidiassov master at iaas.msu.ru
Mon Sep 15 20:25:15 CEST 2014


Dear Hans,

> well, they're just not treated special

IMHO, they have to be treated special.

> you can try this (untested)

I have tested it. It adds nice enhancement, but does not fix the bug
In the following case
local a = {}
a["e"] = "blabla"
a["t"] = "true"
a["f"] = "false"
a["x"] = true
a["y"] = false
a["z"] = nil

your new lpdf.checkedkey correctly fetches "t" and "f", where the old
one failed.
And your new lpdf.checkedkey fails for "e" - if I attempt to fetch it
as boolean I get false instead of nil.
(That is caused by toboolean returning false for unconvertible data -
unlike tonumber).

But I did not complain about reading strings!

My problem was with "y".
Both your new and old lpdf.checkedkey fetch it as nil instead of false.
My (somewhat ugly) idea of the fix is the following

local function lpdf.checkedkey(t,key,variant)
    local pn = t and t[key]
    if pn then
        local tn = type(pn)
        if tn == variant then
            if variant == "string" then
                return pn ~= "" and pn or nil
            elseif variant == "table" then
                return next(pn) and pn or nil
            else
                return pn
            end
        elseif tn == "string" then
            if variant == "number" then
                return tonumber(pn)
            elseif variant == "boolean" then
                 if     pn == "true" then
                   return true
                elseif pn == "false" then
                   return false
                end
          end
        end
    elseif t and t[key] ~= nil and variant == "boolean" and
type(t[key]) == "boolean" then
        return t[key]
    end
end

Michail


More information about the ntg-context mailing list