Skip to content

No way to fail from an initializer in class #2

@andrewstarks

Description

@andrewstarks

Consider:

local ml = require'ml'
local Class = ml.class
tostring = ml.tstring
local My_Class = Class()

function My_Class:_init(msg)
    self.salt = "For the Win!"
    if type(msg) ~= "table" then
        return nil, "need a table with arguments to process for this class!"
    end
    --do some stuff...
    self.butter = "America's Food Sauce!"
    return self
end
local x, err = My_Class("i'm not smart")

print(x, err)
--> {salt="For the Win!"}   nil

Using ml.class, how can it be made possible to fail an initialization? That is, I wish that I could say "if this jackal doesn't pass me what I need to make the object, return nil, errmsg"

As it is, I have to do a separate test, post instantiation to see if the object got made or not (by checking some kind of object flag).
I read the documentation, but couldn't find the answer. I think I could patch ml.class to do it, but didn't know if I was missing some obvious design decision that I'm not following...

Thanks!

-Andrew

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions