New to autoit, what is wrong with this variable? - mysql

so today I just started learning this language, and I'm trying to make my script with parts of example scripts from https://www.autoitscript.com/autoit3/docs/functions.
I'm trying to run a mysql query and I'm getting "Variable Undeclared" error even if it declared as a Global one (atleast i think i declared it as one..)
Basically what my script should do is make an ID for every machine in my LAN store it into a txt file in AppData and then insert it into a db.
#include <MsgBoxConstants.au3>
#include <FileConstants.au3>
#include "EzMySql.au3"
#include <Array.au3>
Example()
Func Example()
$id = Random(1, 1000, 1);Numar random de la 1 la 100
Local Const $sFilePath = #AppDataDir & "\id.txt" ; Selectare %appdata% si id.txt
Local $iFileExists = FileExists($sFilePath)
If $iFileExists Then
Else
; Create a temporary file to write data to.
If Not FileCreate($sFilePath, $ID & #CRLF) Then Return MsgBox($MB_SYSTEMMODAL, "", "O eroare s-a produs in timp ce se scria fila temporara")
; Open the file for writing (append to the end of a file) and store the handle to a variable.
Global $hFileOpen = FileOpen($sFilePath, $FO_APPEND)
If $hFileOpen = -1 Then
MsgBox($MB_SYSTEMMODAL, "", "O eroare s-a produs in timp ce se citea fila.")
Return False
EndIf
; Read the contents of the file using the handle returned by FileOpen.
Global $sFileRead = FileRead($hFileOpen)
; Close the handle returned by FileOpen.
FileClose($hFileOpen)
EndIf
EndFunc
; Create a file.
Func FileCreate($sFilePath, $sString)
Local $bReturn = True ; Create a variable to store a boolean value.
If FileExists($sFilePath) = 0 Then $bReturn = FileWrite($sFilePath, $sString) = 1 ; If FileWrite returned 1 this will be True otherwise False.
Return $bReturn ; Return the boolean value of either True of False, depending on the return value of FileWrite.
EndFunc ;==>FileCreate
$name=#ComputerName
If Not _EzMySql_Startup() Then
MsgBox(0, "Error Starting MySql", "Error: "& #error & #CR & "Error string: " & _EzMySql_ErrMsg())
Exit
EndIf
If Not _EzMySql_Open("127.0.0.1", "root", "", "vrgaming", "3306") Then
MsgBox(0, "Error opening Database", "Error: "& #error & #CR & "Error string: " & _EzMySql_ErrMsg())
Exit
EndIf
If Not _EzMySql_Exec("INSERT INTO `lan` (id, nume) VALUES ('"& $sFileRead &"', '"& $name &"')") Then
MsgBox(0, "Error opening Database", "Error: "& #error & #CR & "Error string: " & _EzMySql_ErrMsg())
Exit
EndIf
_EzMySql_Close()
_EzMySql_ShutDown()
Exit

There are a number of logic issues with the code, that makes it a little tricky to follow.
The error in this case is almost certainly caused because "id.txt" exists, and so $iFileExists evaluates to true, and the global variable is never created.
Then you are creating a new "id.txt", for writing, before reading all the data, so $sFileRead will always be blank and FileRead will set #error as you are trying to read from a file opened for writing.
Now, I think you want the $sFileRead to be whatever the contents of id.txt is, and id.txt should be created with a new random id if it doesn't exist. If so then you need to move the code that opens and reads the file outside of the Else...Endif block (in addition to changing FileOpen to use $FO_READ).
This answer doesn't address the questionable programming practice and code structure.

Related

How to run an AutoIt script and call a function from it?

CONVERTER.au3 converts webp to png using dwebp:
Convert()
Func Convert()
$hSearch = FileFindFirstFile(#ScriptDir & "\*.webp")
$sFileName = FileFindNextFile($hSearch)
$Split = StringSplit($sFileName, ".")
;~ MsgBox(0,'',$Split[1])
Run("dwebp.exe " & $sFilename & " -o " & $Split[1] & ".png")
EndFunc
Func Troubleshoot()
Convert()
Local $hSearch
If $hSearch = -1 Then
$desktopCON = "supported"
Else
$desktopCON = "unsupported"
EndIf
FileClose($hSearch)
Exit
EndFunc
I need to run CONVERTER.au3 and call a specific function from it. I tried this but doesn't seem to work:
Run("D:\SCRIPT\NEW\CONVERTER.au3 Call(Convert)")
Parameters are referenced with the $CmdLine array. The first element ($CmdLine[0] is the number of parameters, $CmdLine[1] is the first parameter, etc.).
If $CmdLine[0] = 0 Then ; standard behavour for no params
Convert()
Exit
EndIf
If $CmdLine[1] = "convert" Then ; param is "convert"
Convert()
Exit
EndIf
If $CmdLine[1] = "troubleshoot" Then ; param is "troubleshoot"
Troubleshoot()
Exit
EndIf
MsgBox(0, "ERRROR", "undefined function: " & $CmdLine[1])
Func Convert()
MsgBox(0, "", "your converting code here")
EndFunc ;==>Convert
Func Troubleshoot()
MsgBox(0, "", "your troubleshooting code here")
EndFunc ;==>Troubleshoot
Execute it from AutoIt with Run('"Converter.au3" foobar')
or from the Windows Command line with just converter.au3 troubleshoot
If no parameter is given, it executes a default function (or whatever you want it to do).

lua function attempt to call global (a nil value)

I am new to lua and i am trying to make a function that receives documents and outputs a table but I am getting the above error. Why??
io.write("How many documents are we evaluating? \nInput: ")
local total_documents=io.read("*n")
io.read()
local docTable = {}
inputDocument()
function inputDocument()
local input
local file
local inputFile = {filename = nil, contents = nil, wordcount = nil}
repeat
io.write("Please enter document (filename.extension): ")
input = io.read()
file =io.open(input)
if file == nil then
print("File does not exist try again")
end
until(file ~=nil)
inputFile.filename = input
return inputFile
end
You need to define inputDocument before using it:
function inputDocument()
...
end
io.write("How many documents are we evaluating? \nInput: ")
...
inputDocument()

Functions don't operate correctly (AutoIt)

So i am trying to make a function out of many functions (i believe it is called recursion, read a post about it earlier on this forum)
When i try to make a number of things into 1 big function so i can call upon it later it doesn't seem to be working but when i take away the "func _hello()" and the "endfunc" from the end, everything seems to be working fine. Can someone please explain this to me. I know the problem is occurring because of the the "Conversion" function but i can't seem to understand why this is happening. Please help, language used here is AutoIt
;;;****Program adds spaces *****
;;;***** the input variable here is $New*****
Global $final
Global $Hexadec
Func _hello()
$DataToBeDecrypted = "55fdaf fdafd"
$2space = $DataToBeDecrypted
$New = $2space
$AddingSpace = StringSplit($New, "")
$Final = ""
If Conversion($AddingSpace[0]) Then
For $Spacing = 1 to $AddingSpace[0] Step 2
$Final = $Final & $AddingSpace[$Spacing] & $AddingSpace[$Spacing+1] & " "
Next
MsgBox(0, "Adding space to the message so it can be converted back to Hex", $Final)
Else
MsgBox(0, "Result", "String does not contain an even number of characters.")
EndIf
Func Conversion($Hexadec)
Return Mod($Hexadec, 2) = 0
EndFunc
;;;***The final value is stored in the $final variable****
;***** Hexadecimals to ASCII*****
;;***Input variable is $HexadecimaltoASCII2******
$HexadecimalToASCII2 =$final
$HexadecimalsToASCII = ChrH($HexadecimalToASCII2)
$Ascii2Hex = Sub($HexadecimalsToASCII)
$v5ar = Chr($HexadecimalsToASCII);char
MsgBox(0,"Hex to ASCII",$HexadecimalsToASCII)
Func ChrH($v8)
Local $v5=""
$A1 = StringSplit($v8, " ")
For $count = 1 To $A1[0]
$v5 &= Chr(Dec($A1[$count]))
Next
Return $v5
endFunc
Func Sub($v8)
Local $v9=""
For $count = 1 To StringLen($v8)
If StringLen(Hex(Asc(StringMid($v8, $count, 1)),2)) = 1 Then
$v9 &= "0" & Hex(Asc(StringMid($v8, $count, 1)))
Else
$v9 &= Hex(Asc(StringMid($v8, $count, 1)),2)
EndIf
If $count <> StringLen($v8) Then $v9 &= " "
Next
Return $v9
endFunc
;*****HEXADECIMAL to ASCII*****
EndFunc
It seems like you never call your Hello() function. To execute a function you have to call it.
Try adding Hello() at the top of the file and it should work.

Corona reading and writing files (first time access)

I'm trying to write a function that will read sound and music states before starting my application.
The problem is: The first time it will run, there will be no data recorded.
First, I tried the suggested JSON function from here and I got this error:
Attempt to call global 'saveTable' (a nil value)
Is there a way to test if the file exists?
Then, I tried this one:
-- THIS function is just to try to find the file.
-- Load Configurations
function doesFileExist( fname, path )
local results = false
local filePath = system.pathForFile( fname, path )
--filePath will be 'nil' if file doesn,t exist and the path is "system.ResourceDirectory"
if ( filePath ) then
filePath = io.open( filePath, "r" )
end
if ( filePath ) then
print( "File found: " .. fname )
--clean up file handles
filePath:close()
results = true
else
print( "File does not exist: " .. fname )
end
return results
end
local fexist= doesFileExist("optionsTable.json","")
if (fexist == false) then
print (" optionsTable = nil")
optionsTable = {}
optionsTable.soundOn = true
optionsTable.musicOn = true
saveTable(optionsTable, "optionsTable.json") <<<--- ERROR HERE
print (" optionsTable Created")
end
The weird thing is that I'm getting an error at the saveTable(optionsTable,"optionsTable.json"). I just can't understand why.
If you have a working peace of code that handles the first time situation it will be enough to me. Thanks.
here's some code to check if the file exist you have to try and open the file first to know if it exist
function fileExists(fileName, base)
assert(fileName, "fileName is missing")
local base = base or system.ResourceDirectory
local filePath = system.pathForFile( fileName, base )
local exists = false
if (filePath) then -- file may exist wont know until you open it
local fileHandle = io.open( filePath, "r" )
if (fileHandle) then -- nil if no file found
exists = true
io.close(fileHandle)
end
end
return(exists)
end
and for usage
if fileExists("myGame.lua") then
-- do something wonderful
end
you can refer to this link for details

Storing a String saved as a Variable in a MySQL database?

In a ruby script that sends information to the TWILIO API, I have a string of characters of characters that their (Twilio's) API outputs. I then have the console output it so I can save it as a variable and reuse it later:
#client = Twilio::REST:Client.new account_sid, auth_token
call = #client.account.calls.create({:from => 'incoming', :to => 'outgoing', :url => 'url', :method => 'GET'})
puts call.sid
This part is functional, but now when I rename the variable (// #incoming_Cid=call.sid //) as to input it into a MySQL database, I bump into an issue. (The 34 character ID has numbers and letters, so I define the datatype as VARCHAR).
begin
dbh = DBI.connect("DBI:Mysql:db_name:localhost",
"user", "pass")
dbh.do ("INSERT INTO calls (column_name)" #//Select the column to insert
"VALUES (incoming_Cid)") #Insert the 34 character string.
dbh.commit
puts "Customer SID has been recorded"
rescue
puts "A database occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
ensure
dbh.disconnect if dbh
end
Right here at the dbh.do ("INSERT INTO calls " line if I put the incoming_Cid variable in the VALUES() instead of seeing a 34-char-string, like CA9321a83241035b4c3d3e7a4f7aa6970d, I literally see 'incoming_Cid' appear in the database when I execute select * in calls.
How can I resolve this issue?
You need to use string interpolation: "VALUES (#{#incoming_Cid})"