Last active
January 26, 2021 17:39
-
-
Save imring/e873a88ad3a915bbc3a408f1997bb423 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local requests = require 'requests' | |
local json = require 'cjson' | |
local url = 'https://api.vk.com/method/%s' | |
local mt = {} | |
-- http://lua-users.org/wiki/CopyTable | |
local function shallowcopy(orig) | |
local orig_type = type(orig) | |
local copy | |
if orig_type == 'table' then | |
copy = {} | |
for orig_key, orig_value in pairs(orig) do | |
copy[orig_key] = orig_value | |
end | |
else -- number, string, boolean, etc | |
copy = orig | |
end | |
return copy | |
end | |
local function send(self, method, data, full_info) | |
local params = shallowcopy(data) | |
params.access_token = self.token | |
params.v = self.v | |
local res = requests.get{url:format(method), params = params} | |
return full_info and res or json.decode(res.text) | |
end | |
function mt.__index(self, index) | |
local v = rawget(self, index) | |
if v ~= nil then return v end | |
local t = shallowcopy(self) | |
if not t.method then t.method = {} end | |
table.insert(t.method, tostring(index)) | |
return setmetatable(t, getmetatable(self)) | |
end | |
function mt.__call(self, data, full_info) | |
return send(self, table.concat(self.method, '.'), data, full_info) | |
end | |
local function new(token, version) | |
return setmetatable({ token = token, v = version, send = send }, mt) | |
end | |
return { new = new } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: