Jump to content

Create a function name after a variable


Recommended Posts

Hello folks!

I'm trying to create a function name after a variable, so I read about Assign and Eval, but this example didn't work:

$Test = "Test"
HotKeySet("{End}", $Test)
Assign("Test", "Test()")
ProcessWait("")

Func Eval("Test")
   MsgBox(0, "", $Test)
EndFunc

This test returns the message "Error: Badly formatted Func statement."
I don't know if this is possible, but as an old brazilian quote says, "Ask don't hurt".

Thanks in advance,

RegiOween

Link to comment
Share on other sites

  • Moderators

RegiOween,

If you want to call a function based on the content of a variable then I would do something like this:

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>

HotKeySet("{END}", "_Test")

$sTest = ""

$hGUI = GUICreate("Test", 500, 500)

$cRadio_1 = GUICtrlCreateRadio("Func_1", 10, 10, 100, 20)
$cRadio_2 = GUICtrlCreateRadio("Func_2", 10, 40, 100, 20)

GUISetState()

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $cRadio_1
            $sTest = "_Func_Name_1"
        Case $cRadio_2
            $sTest = "_Func_Name_2"
    EndSwitch
WEnd

Func _Test()
    If $sTest <> "" Then
        Call($sTest)
    EndIf
EndFunc

Func _Func_Name_1()
    MsgBox($MB_SYSTEMMODAL, "Hi", "Func 1")
EndFunc
Func _Func_Name_2()
    MsgBox($MB_SYSTEMMODAL, "Hi", "Func 2")
EndFunc

Please ask if you have any questions.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

You can't do it that way, but you can create a variable that references the function instead.

$Test = Test
HotKeySet("{End}", $Test)

ProcessWait("")

Func Test()
   MsgBox(0, "", "Test")
   Exit
EndFunc

There's no such thing as a run time function name.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Melba,

Thanks for the quick response, but in your example, you had to explicitly define the name of the functions anyway, and that's what I'm trying to avoid.

My purpose is to build a customizable horizontal toolbar for Photoshop (it's done already, but using literal names, of course). Just a snippet below:

$PHOTOSHOP = "[CLASS:Photoshop]"
$TOOL = "Brightness_Contrast"
$ICONS = "Icons\"
$BRIGHTNESS_CONTRAST = GUICtrlCreateButton("", 0, 0, 28, 28, $BS_BITMAP)
GUICtrlSetImage(-1, $ICONS & $TOOL & ".bmp")
GUICtrlSetTip(-1, $TOOL)
GUICtrlSetOnEvent($BRIGHTNESS_CONTRAST, "Brightness_Contrast")

Func Brightness_Contrast()
  WinActivate($PHOTOSHOP)
  ControlSend($PHOTOSHOP, "", "", "^b")
EndFunc

This is just the code of one button, but my custom toolbar had dozens already, so I would like to avoid repeating strings every time I put a new button. If you call me lazy, you're damn right... :D

Link to comment
Share on other sites

As I stated previously, there's no such thing as a run time function name, they have to be explicitly named prior to running the script.

Frankly, I can't see how a run-time named function would work in the real world, or why you would want to not know the names of your functions if you're the author of the script.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

  • Moderators

RegiOween,

A pity you did not explain more clearly in the OP - then the responders would not have wasted their time replying to the originally posted problem which has little to do with what you actually want.

Perhaps something like this might be useful:

$BRIGHTNESS_CONTRAST = GUICtrlCreateButton("", 0, 0, 28, 28, $BS_BITMAP)
GUICtrlSetOnEvent($BRIGHTNESS_CONTRAST, "_Toolbar_Buttons")

$OTHER_BUTTON = GUICtrlCreateButton("", 0, 0, 28, 28, $BS_BITMAP)
GUICtrlSetOnEvent($OTHER_BUTTON, "_Toolbar_Buttons")

Func _Toolbar_Buttons()
    WinActivate($PHOTOSHOP)
    $sSend = ""
    Switch @GUI_CtrlId
        Case $BRIGHTNESS_CONTRAST
            $sSend = "^b"
        Case $OTHER_BUTTON
            $sSend = "!Foo"
    EndSwitch
    If $sSend Then
        ControlSend($PHOTOSHOP, "", "", $sSend)
    EndIf
EndFunc   ;==>_Toolbar_Buttons

Now you have just the one function and what you actually send is determined by which button you press. Adding a button just requires a new Case.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Quote

Frankly, I can't see how a run-time named function would work in the real world, or why you would want to not know the names of your functions if you're the author of the script.

Brew,

The main reason (not much important, I admit) is to make the task to add new buttons easier, avoid typing repeated strings.

In the snippet code I gave above, if evaluated variable content would be possible to create functions, I could just label one variable with the name of the button ($TOOL in the example), and all the subsequent names could use its content.

Extravagant ideas from a lazy programmer... :D

Link to comment
Share on other sites

How would that work? You'd have a new button pointing to what? Just because you give it a function name, if the function doesn't  exist yet it won't do anything except error out.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Melba,

I apologize if I wasn't clear in my first post about what I was intended to do. And your last code is much more simple and efficient (just one function for all the buttons) than what I did in my own code (one function for each button). Many thanks!

Brew,

I was thinking in something like this:

Assign("VAR", "String()")

Func Eval("VAR")
...
EndFunc

In this little example, I guess it would be possible to create a function called String(), based on the content of $VAR, but I was wrong, so Melba provided a much better way to handle my purpose. Many thanks for your attention!

RegiOween

Edited by RegiOween
Link to comment
Share on other sites

  • Moderators

RegiOween,

Glad I could help.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Melba's solution is superior but there exists another possibility closer to what you had in mind in the first time: Execute() would allow just that. But, again, prefer Melba's code.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

jchd,

Thanks to comment, but I didn't get how Execute can come closer to what I had in mind in the first time. Can you please show me some example?

To AutoIt developers and experts, considering it's already possible to dynamically deal with variables using Assign and Eval, don't you think it would be a nice improvement to use parameters to create a function name?

Link to comment
Share on other sites

I can't see a good reason why this would be useful, but you can always use something like this (keeping in mind that Melba's code is FAR better):

Local $func = "MyFunction_"
Local $SomeParameter = "Hello!"
Execute($func & "xyz" & "($SomeParameter)")
Local $i = 40
Execute($func & ($i + 3) & "($SomeParameter & @LF & 'little world!')")

Func MyFunction_xyz($s)
    MsgBox(0, "", $s)
EndFunc

Func MyFunction_43($s)
    MsgBox(0, "", $s)
EndFunc

 

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

  • Moderators

RegiOween,

Quote

To AutoIt developers and experts, considering it's already possible to dynamically deal with variables using Assign and Eval, don't you think it would be a nice improvement to use parameters to create a function name?

In short - No! Use code such as I suggested, as jchd as pointed out at least twice.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Hello, jchd!

Thanks for the quick response, and now I got your point, but I think this solution would fit just if I wanted to dynamically execute a function, but the original idea starting the post was actually create a function dynamically, using a variable content.

As I stated before, I was trying to create a function after a button label, so I could use this same string in any part of the code related to the button. Something like this:

$Tool = "Save_Image"
Assign(Eval("Tool"), GUICtrlCreateButton("", 1, 1, 28, 28, $BS_BITMAP))
GUICtrlSetImage(-1, $Tool & ".bmp")
GUICtrlSetTip(-1, StringReplace($Tool, "_", " "))
GUICtrlSetOnEvent(-1, $Tool)
Func Eval($Tool) & "()"
  Send("^s")
EndFunc

As you can see, the intention was to create a function named "Save_Image()" using the content of the variable $Tool, since the variable $Save_Image was already dynamically created through Assign.

Of course this code didn't work, because Func statement doesn't accept parameters in its name, so that's why I think it would be an improvement to the language if that would be possible.

Anyway, Melba solution worked perfectly to me, so I'm using it in my project.

Thanks again,

RegiOween

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...