#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
#define GV_NAME "TestGlobalVariableGet"
#define GV_VALUE 1.23
//+------------------------------------------------------------------+
//| 脚本程序起始函数 |
//+------------------------------------------------------------------+
void OnStart()
{
//--- 将该值设置到名为 GV_NAME 的客户端终端的全局变量
if(!GlobalVariableSetValue(GV_NAME, GV_VALUE))
return;
//--- 获取名为 GV_NAME 的客户端全局变量的实际值
//--- 因为当使用调用 GlobalVariableGet 的第一种形式时零是错误信号,
//--- 在读取结果时,有必要分析最后一个错误代码
double dvalue=GlobalVariableGet(GV_NAME);
if(dvalue==0 && GetLastError()!=0)
{
Print("GlobalVariableGet() failed. Error ", GetLastError());
return;
}
//--- 显示获得的结果
PrintFormat("The first form of the GlobalVariableGet() function call returned the value %.2f", dvalue);
//--- 将名为 GV_NAME 的客户端的全局变量设置为零值
if(!GlobalVariableSetValue(GV_NAME, 0))
return;
//---使用调用的第一种形式,我们得到名为 GV_NAME 的客户端全局变量的布尔值
bool bvalue=GlobalVariableGet(GV_NAME);
if(!bvalue && GetLastError()!=0)
{
Print("GlobalVariableGet() failed. Error ", GetLastError());
return;
}
//--- 显示获得的结果
PrintFormat("The first form of the GlobalVariableGet() function call returned the value %.2f with type bool as %s", bvalue, (string)bvalue);
//--- 将名为 GV_NAME 的客户端的全局变量设置为非零值
if(!GlobalVariableSetValue(GV_NAME, GV_VALUE*100.0))
return;
//--- 再次读取名为 GV_NAME 的客户端全局变量的布尔值
bvalue=GlobalVariableGet(GV_NAME);
if(!bvalue && GetLastError()!=0)
{
Print("GlobalVariableGet() failed. Error ", GetLastError());
return;
}
//--- 显示获得的结果
PrintFormat("The first form of the GlobalVariableGet() function call returned the value %.2f with type bool as %s", bvalue, (string)bvalue);
//--- 使用 GlobalVariableGet 调用的第二种形式获取名为 GV_NAME 的客户端全局变量的实际值
if(!GlobalVariableGet(GV_NAME, dvalue))
{
Print("GlobalVariableGet() failed. Error ", GetLastError());
return;
}
//--- 将得到的实值转换为 long 类型的整数并显示结果
long lvalue=(long)dvalue;
PrintFormat("The second form of the GlobalVariableGet() function call returned the value %.2f with type long as %I64d", dvalue, lvalue);
//--- 使用后删除名为 GV_NAME 的客户端全局变量
if(!GlobalVariableDel(GV_NAME))
{
Print("GlobalVariableDel() failed. Error ",GetLastError());
}
/*
结果:
The first form of the GlobalVariableGet() function call returned the value 1.23
The first form of the GlobalVariableGet() function call returned the value 0.00 with type bool as false
The first form of the GlobalVariableGet() function call returned the value 1.00 with type bool as true
The second form of the GlobalVariableGet() function call returned the value 123.00 with type long as 123
*/
}
//+------------------------------------------------------------------+
//| 将该值设置到终端全局变量。 |
//| 如果没有变量,则创建它 |
//+------------------------------------------------------------------+
bool GlobalVariableSetValue(const string gv_name, const double value)
{
if(GlobalVariableSet(gv_name, value)==0)
{
Print("GlobalVariableSet() failed. Error ",GetLastError());
return(false);
}
return(true);
}
|