From a589b79e6c5c238df3fbab05a81c7f186cddcaad Mon Sep 17 00:00:00 2001 From: lionsoul Date: Fri, 5 Oct 2018 21:46:21 +0800 Subject: [PATCH] lua binding module interface stdlize with new and ip2long method access by . support --- binding/lua/Ip2region.lua | 13 ++++++++++--- binding/lua/README.md | 5 +++-- binding/lua/testSearcher.lua | 6 +++--- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/binding/lua/Ip2region.lua b/binding/lua/Ip2region.lua index 7f7604e..6215bf3 100644 --- a/binding/lua/Ip2region.lua +++ b/binding/lua/Ip2region.lua @@ -46,9 +46,10 @@ construct method @param obj @return Ip2region object --]] -function _M:new(obj) - obj = obj or {}; +function _M.new(dbFile) + obj = {}; setmetatable(obj, _M); + obj.dbFile = dbFile; return obj; end @@ -80,7 +81,13 @@ internal function to convert the string ip to a long value @param ip @return Integer ]]-- -function _M:ip2long(ip) +function _M.ip2long(self, ip) + -- dynamic arguments checking + -- to support object.ip2long and object:ip2long access + if ( type(self) == "string") then + ip = self; + end + local ini = 1; local iip = 0; local off = 24; diff --git a/binding/lua/README.md b/binding/lua/README.md index d682691..cc22ee4 100644 --- a/binding/lua/README.md +++ b/binding/lua/README.md @@ -27,11 +27,12 @@ ip2region>> * 2, 通过如下流程在你的lua程序中使用 ```lua -- 包含模块 -require "Ip2region"; +local Ip2region = require "Ip2region"; -- 创建查询对象 -- 设置ip2region.db的文件地址,dbFile表示ip2region.db数据库文件的地址 -local ip2region = Ip2region:new({dbFile = "ip2region.db file path"}); +-- 注意new方法是通过“.”调用,而不是“:” +local ip2region = Ip2region.new("ip2region.db file path"); -- 也可以通过如下方式设置dbFile -- ip2region.dbFile = "ip2region.db file path"; diff --git a/binding/lua/testSearcher.lua b/binding/lua/testSearcher.lua index ce4d759..9a4f3ec 100644 --- a/binding/lua/testSearcher.lua +++ b/binding/lua/testSearcher.lua @@ -12,14 +12,14 @@ Usage: lua testSearcher.lua [ip2region db file] [algorithm] os.exit(); end -require "Ip2region"; +local Ip2region = require "Ip2region"; -- local cjson = require "cjson"; -- local socket = require "socket"; -- check and parse the dbFile and the method algorithm -- Create a new ip2region object by the new interface -local ip2region = Ip2region:new({dbFile = arg[1]}); +local ip2region = Ip2region.new(arg[1]); -- reset the dbFile by the follow two ways: -- ip2region.dbFile = arg[1]; @@ -58,7 +58,7 @@ while ( true ) do break; elseif ( line == "quit" ) then break; - elseif ( ip2region:ip2long(line) == nil ) then + elseif ( ip2region.ip2long(line) == nil ) then print("Invalid ip address=", line); else local data;