lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


 

In my lib - https://github.com/kurapica/PLoop, there is a structure system can be used to do those type validation, nest, default, require and others, for your example, its like

 

require "PLoop" (function(_ENV)

            struct "UI" {

                        mainwindow = {

                                    require = true,

                                    type = struct {

                                                size = {

                                                            require = true,

                                                            type = struct {

                                                                        width = { require = true, Number },

                                                                        height = { require = true, Number },

                                                            }

                                                }

                                    }

                        }

            }

 

            -- Error: xxx.lua:18: Usage: UI(mainwindow) - the mainwindow.size.height can't be nil

            ui = UI { mainwindow = { size = { width = 200 } } }

end)

 

You can also define template struct like Range

 

require "PLoop" (function(_ENV)

            __Arguments__{ Number, Number }

            struct "Range" (function(_ENV, min, max)

                        __base = Number

 

                        function __valid(val)

                                    if val < min or val >  max then

                                                return "The %s must bwtween " .. min .. " and " .. max

                                    end

                        end

            end)

 

            struct "Size" {

                        -- it's a little weird, but I have no other way to pass multi template params

                        width = Range[{0, 400}]

            }

 

            -- Usage: Size(width) - The width must bwtween 0 and 400

            v = Size{ width = 700 }

end)