--[[
AddFuncUndeclaredVars()
Add function uneclared variables.
Author: G.Sandler (CreatoR)
--]]
-- Get the current line.
local iCurr_Pos = editor.CurrentPos
local iLine = editor:LineFromPosition(iCurr_Pos)
local sLine = editor:GetLine(iLine)
if sLine == nil then
print("- Cursor not on function definition.")
return
end
-- Get function name in original case registry
local sFunc_Name = sLine:match("^%s*[Ff][Uu][Nn][Cc] %s*([%w_]*)")
-- First we check if it's a function (in lower case).
if not sFunc_Name then
print("- Cursor not on function definition.")
return
end
-- Set up variables we'll be using throughout.
local sUnDclrd_Vars = ""
local sFunc_Body = sLine
local iFunc_Line = iLine
local aParams = sLine:gmatch("(%$[%w_]*)")
local aScope = {"local", "global", "dim", "const", "static"}
local aVars = {}
-- Get function body and vars
while iLine < editor.LineCount - 1 do
iLine = iLine + 1
sLine = editor:GetLine(iLine)
if sLine:lower():match("^%s*endfunc") then
sFunc_Body = sFunc_Body .. sLine
break
end
-- Ignore commented lines
if sLine:match("^%s*;") == nil then
sFunc_Body = sFunc_Body .. sLine
for var, str in sLine:gmatch("(%$[%w_]+)%s*=%s*") do
aVars[var] = var
end
end
end
-- Get current doc content and remove all functions and all commented lines from it
local sDoc_Read = editor:GetText():lower():gsub("[\r\n^]%s*func %s*([%w_]*.-endfunc)", "")
sDoc_Read = sDoc_Read:gsub("[\r\n^]%s*;[^\r\n]*", "")
sDoc_Read = sDoc_Read:gsub("[\r\n^]%s*#cs%s*.-#ce", "")
sDoc_Read = sDoc_Read:gsub("[\r\n^]%s*#comments%-start%s*.-#comments%-end", "")
for sKey, sVar in pairs(aVars) do
iFound = 0
-- Check if the vars not declared in function params
for sParam, str in aParams do
if sVar:lower() == sParam:lower() then
iFound = 1
break
end
end
-- Check if the vars not declared in function itself
if iFound == 0 then
-- for i = 1, #aScope do
for _, sScope in ipairs(aScope) do
if sFunc_Body:lower():match("[\r\n^]%s*" .. sScope:lower() .. " .*" .. sVar:lower() .. "%s*[=,\r\n]") then
iFound = 1
break
end
end
end
-- Check if the vars not declared globaly in entire file (only current script ATM)
if iFound == 0 and sDoc_Read:match("[\r\n^]%s*global .*" .. sVar:lower() .. "%s*[=,\r\n]") then
iFound = 1
end
if iFound == 0 then
if sUnDclrd_Vars ~= "" then
sUnDclrd_Vars = sUnDclrd_Vars .. ", "
end
sUnDclrd_Vars = sUnDclrd_Vars .. sVar
end
end
if sUnDclrd_Vars == "" then
print("> Undeclared variables not found in \"" .. sFunc_Name .. "\" function")
else
editor:LineEnd()
editor:NewLine()
editor:ReplaceSel("Local " .. sUnDclrd_Vars)
editor:NewLine()
editor:GotoPos(iCurr_Pos)
end