Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util.warn does not warn against unexisting table members #9

Open
jucor opened this issue Jul 26, 2013 · 3 comments
Open

util.warn does not warn against unexisting table members #9

jucor opened this issue Jul 26, 2013 · 3 comments

Comments

@jucor
Copy link
Contributor

jucor commented Jul 26, 2013

Hi Jeff, Andreas @akfidjeland

I just noticed (the hard way) that util.warn only warns against reading unexisting variables, not unexisting table members:

require 'util.warn'

-- generates an error
-- local x = y

local t = {}
-- does not generate an error
local x = t.y

This is very problematic when using object-style, since self is always a table: we can thus read from inexisting fields. Would it be possible to warn against this, the same way you check for unexisting members in _G?

@fidlej
Copy link
Contributor

fidlej commented Jul 30, 2013

I'm posting the code for the simplest checking here.
If you want to check torch classes and nested tables,
some extra logic would need to be integrated.
You can experiment with the metatable methods __index and __newindex.

local function guardReads(table)
    setmetatable(table, {
        __index = function (table, key)
            error("missing key: "..tostring(key), 2)
        end,
    })
end

local t = {}
guardReads(t)
-- will generate an error
local x = t.y

@jucor
Copy link
Contributor Author

jucor commented Jul 30, 2013

Thanks Ivo. As discussed by email, is it possible to package this guardReads to util.warn? I can then call it on self in the __init() of my class.

@fidlej
Copy link
Contributor

fidlej commented Jul 30, 2013

I worry that calling guardReads(self) would not work correctly.
The torch class has already an existing metatable. The metatable provides a fallback to read attributes from the parent.

You can start using the above guardReads() in your code and discover the problems.
In other words: pull-requests are welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants